【问题标题】:VBA how are strings comparedVBA如何比较字符串
【发布时间】:2016-02-16 22:25:04
【问题描述】:

我想弄清楚为什么两个字符串不相等。这是我的即时窗口:

?strg2
Table 4.662: MIMCAP Design Rules (Part 2)

?strg1
Table 4.662: MIMCAP Design Rules (Part 2)

?strg1 = strg2
False
?strg2 > strg1
True

这里是我的变量是如何确定的:

strg1 = objSelectionChange.Text
strg1 = Replace(strg1, vbNewLine, "")
strg1 = Trim(strg1)

strg2 = objSelectionChange.Sentences(1).Text
strg2 = Replace(strg2, vbNewLine, "")
strg2 = Trim(strg2)

随后的If ((Len(strg2) < 230) And (strg2 <> strg1)) 测试表明这些特定值不应该通过,因为它们应该是相等的。我认为这是一些空白,所以我使用了TrimReplace,但是由于某种原因,这两个字符串在技术上仍然不相等。有什么想法吗?

【问题讨论】:

  • Len() 为两者返回什么?您可以做的另一件事是循环原始 Range 中的每个字符并列出其 ANSI 值(ASC 函数),然后比较这两个列表。
  • 如果您遍历所有字符并且您处于国际环境中,那么我将再次支持AscW 而不是Asc

标签: string vba ms-word compare


【解决方案1】:

我能想到有两件事可以防止两个字符串相等:

(1) 您可能想研究一下 VBA 中的不同比较选项。查看以下内容以获得更多帮助: https://msdn.microsoft.com/en-us/library/8t3khw5f.aspx.

(2) 如果您在国际上工作,那么a 看起来像a,但实际上它们并不相同。第一个可以使用Selection.Value = ChrW(97)(使用拉丁字母)来实现,第二个是Selection.Value = ChrW(1072)(来自西里尔键盘)。它们看起来(视觉上)相同,但实际上与 VBA 不同。

注意:不要在直接窗口中尝试第二个,因为您可能只会看到 ChrW(1072) 的 ?。而是将这两个值(如上所示)分配给工作表中的两个不同单元格,您会看到它们看起来相同,但实际上并非如此:

Public Sub Comparison()

Sheets(1).Cells(2, 1).Value = ChrW(97)
Sheets(1).Cells(2, 2).Value = ChrW(1072)
Sheets(1).Cells(2, 3).Formula = "=$A$1=$B$2"

End Sub

作为最后一个选项,您可以逐个字母进行比较以手动找出差异。下面的 sub 将做到这一点(有点冗长):

Option Compare Binary

Public Sub StringCompare()
Dim strText As String
Dim strSentence As String

strText = "Table 4.662: MIMCAP Design Rules (Part 2)"      'First string to compare to.
strSentence = "Table 4.662: MIMCAP Design Rules (Part 2)"  'Second string to compare to.

Dim lngLetterCount As Long

For lngLetterCount = 1 To IIf(Len(strText) > Len(strSentence), Len(strText), Len(strSentence))
    Debug.Print "Letter " & Right("  " & lngLetterCount, 3) & ": " _
        & Mid(strText, lngLetterCount, 1) _
        & " (" & Right("00" & AscW(Mid(strText, lngLetterCount, 1)), 3) & ")" _
        & " - " _
        & Mid(strSentence, lngLetterCount, 1) _
        & " (" & Right("00" & AscW(Mid(strSentence, lngLetterCount, 1)), 3) & ") " _
        & IIf(AscW(Mid(strText, lngLetterCount, 1)) = AscW(Mid(strSentence, lngLetterCount, 1)), "", "<-- Err")
Next lngLetterCount
If Len(strText) >= lngLetterCount Then
    Debug.Print "The text string is longer than the sentence string. Ther is no match for '" & Mid(strText, lngLetterCount) & "' in sentence."
End If
If Len(strSentence) >= lngLetterCount Then
    Debug.Print "The sentence string is longer than the text string. Ther is no match for '" & Mid(strSentence, lngLetterCount) & "' in text."
End If

End Sub

【讨论】:

  • 这些是来自美国的内部文档,而且这两个字符串无论如何都来自同一个文档。 strg1 是选中的文本,strg2 是选中的文本句子。我比较了 Cindy Meister 建议的长度,发现 strg1 是 42 个字符,strg2 是 43 个字符。我目前正在研究一种方法来找出 AscW 的额外字符是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多