VBA如何比较字符串

时间:2016-02-16 22:25:05

标签: string vba ms-word compare

我想弄清楚为什么两个字符串彼此不相等。这是我的直接窗口:

?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,但由于某些原因,这两个字符串在技术上仍然不相同。有什么想法吗?

1 个答案:

答案 0 :(得分: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

作为最终选项,您可以逐字比较以手动找出差异。以下子将做到这一点(有点冗长):

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