VBA function InSTR - How to use asterisk (as any other charakter) in searched phrase?

孤人 提交于 2020-06-17 15:35:27

问题


In Excel when we try to find some phrase we can put asterisk * inside as any other character. But how to do it inside VBA macro? For example below; I want to find the secName by searching the value of firName with asterisk but id doesn't work. I suppose the problem is that VBA thinks that i want to find exactly * as normal character instead of anything.

Dim firName, secName As String

firName = "Da*"
secName = "Daniel"

search = InStr(1, secName, firName, vbTextCompare)

MsgBox (search)

Is it possible to use asterisk * in the way I described?


回答1:


You can either do a FuzzySearch like: Matching similar but not exact text strings in Excel VBA projects, …

… or you can use the The Levenshtein Distance to find out how similar 2 strings are which is probably more accurate but needs O(n*m) time for calculation. So don't use it on very long strings.

Function Levenshtein(str1 As String, str2 As String) As Long
    Dim arrLev As Variant, intLen1 As Long, intLen2 As Long, i As Long
    Dim j As Long, arrStr1 As Variant, arrStr2 As Variant, intMini As Long

    intLen1 = Len(str1)
    ReDim arrStr1(intLen1 + 1)
    intLen2 = Len(str2)
    ReDim arrStr2(intLen2 + 1)
    ReDim arrLev(intLen1 + 1, intLen2 + 1)

    arrLev(0, 0) = 0
    For i = 1 To intLen1
        arrLev(i, 0) = i
        arrStr1(i) = Mid(str1, i, 1)
    Next i

    For j = 1 To intLen2
        arrLev(0, j) = j
        arrStr2(j) = Mid(str2, j, 1)
    Next j

    For j = 1 To intLen2
        For i = 1 To intLen1
            If arrStr1(i) = arrStr2(j) Then
                arrLev(i, j) = arrLev(i - 1, j - 1)
            Else
                intMini = arrLev(i - 1, j) 'deletion
                If intMini > arrLev(i, j - 1) Then intMini = arrLev(i, j - 1) 'insertion
                If intMini > arrLev(i - 1, j - 1) Then intMini = arrLev(i - 1, j - 1) 'deletion

                arrLev(i, j) = intMini + 1
            End If
        Next i
    Next j

    Levenshtein = arrLev(intLen1, intLen2)
End Function

The smaller the returned number is the more similar are the strings. For example:

Debug.Print Levenshtein("OFFICE CLUB, S.A.", "OFFICE CLUB SA")   'returns 3
Debug.Print Levenshtein("OFFICE CLUB, S.A.", "OFFICE CLUB S.A.") 'returns 1

The second strings are more similar than the first ones.



来源:https://stackoverflow.com/questions/53472785/vba-function-instr-how-to-use-asterisk-as-any-other-charakter-in-searched-ph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!