【问题标题】:How can I search whole word not partial match in string in VBA如何在 VBA 中搜索整个单词而不是部分匹配的字符串
【发布时间】:2017-02-27 04:41:16
【问题描述】:

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

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

这段代码用 N 替换了 north,这很好,但它也用 Nern 替换了 Northern,这是我不想要的。如何只比较整个单词?

在 php 中是 == 但我不确定在 VBA 中,顺便说一下我在 MS Access VBA 中使用它。

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    这是您所问问题的解决方案

    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
    

    单词匹配: WordMatch = 标志 结束函数

    【讨论】:

      【解决方案2】:

      你可以这样

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多