虽然substring有效,但Excel VBA InStr返回0

tan*_*tan 3 excel vba excel-vba

在这段代码中,我试图检查用户输入的输入(txtList)是否可以在数据列表(txtList)中找到.以下代码返回0(虽然"John Ho"和"Ho Tee Nee,John"是完全相同的人,但未找到子字符串.有人可以请教我如何解决这个问题吗?

'code returns 0 (substring not found)
Dim txtList As String, txtInput As String
txtList = "Ho Tee Nee, John"
txtInput = "John Ho"
Debug.Print InStr(1, txtList, txtInput, vbTextCompare)
Run Code Online (Sandbox Code Playgroud)

小智 7

拆分搜索条件并查找每个部分.

Dim i As Long, txtList As String, txtInput As Variant
txtList = Chr(32) & "Ho Tee Nee, John" & Chr(32)
txtInput = Split("John Ho", Chr(32))

For i = LBound(txtInput) To UBound(txtInput)
    If Not CBool(InStr(1, txtList, Chr(32) & txtInput(i) & Chr(32), vbTextCompare)) Then Exit For
Next i

If i > UBound(txtInput) Then
    Debug.Print "all parts match"
Else
    Debug.Print "incomplete match"
End If
Run Code Online (Sandbox Code Playgroud)

这是一个不区分大小写的搜索.对于区分大小写的搜索,将vbTextCompare更改为vbBinaryCompare.