如何在VBA中搜索字符串中的全字而非部分匹配

时间:2016-10-18 03:55:18

标签: vba ms-access access-vba

我正在尝试替换字符串中的单词。下面的代码执行替换工作,但它也取代了我不希望它做的部分匹配。

If InStr(inputString, "North") Then
    inputString = Replace(inputString, "North", "N")
End If

这段代码用N代替北方,这很好,但它也用Nern取代了Northern,这是我不想要的。我怎样才能比较整个单词?

在php中它是==但我在VBA中不确定,就像我在MS Access VBA中使用它一样。

2 个答案:

答案 0 :(得分:0)

你可以这样做

If InStr(inputString, "North") Then inputString = Trim(Replace(Replace(Replace(inputString & " ", " North ", "  North  "), " North ", " N"), "  ", " "))

的“收缩”
If InStr(inputString, "North") Then
    inputString = inputString & " " '<-- add a space at the end to catch "North" should it be the last "word" in a possible "...North" string
    inputString = Replace(inputString, " North ", "  North  ") '<-- double spaces before and after any " North " occurrence, necessary for subsequent statement to properly work should there be more than one " North " occurrence
    inputString = Replace(inputString, " North ", " N") '<-- make the "core" replacement
    inputString = Replace(Replace(inputString, " North ", " N"), "  ", " ") '<-- make all double spaces occurrences as single ones
End If

答案 1 :(得分:0)

以下是您提出的问题的解决方案

Public Function WordMatch(ByVal Text As String, ByVal Word As String) As Boolean
Dim RightChar As String
Dim LeftChar As String
Dim IStart As Integer
Dim IEnd As Integer
Dim Flag As Boolean
Dim Alphabet As String
 Alphabet = "abcdefghijklmnopqrstuvwxyz"
 Flag = True

IStart = InStr(Text, Word)

If Not (IStart > 0) Then
    Flag = False
Else
    IEnd = IStart + Len(Word) - 1

    If (IStart = 1 And IEnd = 1) Then GoTo WordMatched

        If IStart > 1 Then
            LeftChar = Mid(Text, IStart - 1, 1)
            'LeftChar = Mid(Text, IStart - 1 - 3, 4)
            'MsgBox "L'" & LeftChar & "' - " & Text & " - " & Word
            If InStr(Alphabet, LeftChar) > 0 Then
                Flag = False
            End If
        End If
        If (IEnd < Len(Text)) Then
            RightChar = Mid(Text, IEnd + 1, 1)
            'RightChar = Mid(Text, IEnd + 1, 4)
            'MsgBox "R'" & RightChar & "' - " & Text & " - " & Word
            If InStr(Alphabet, RightChar) > 0 Then
                Flag = False
            End If
        End If

    'End If

End If

WordMatched:     WordMatch =标志 结束功能