Excel VBA InStr返回0,但子字符串有效

Excel VBA InStr返回0,但子字符串有效,vba,excel,Vba,Excel,在这段代码中,我试图检查用户输入的输入(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" De

在这段代码中,我试图检查用户输入的输入(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)

拆分搜索条件并查找每个条目

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

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

这是因为它正在查找完整的匹配项。它不会分割单词并单独查找。它必须在其他字符串而不是部分中找到完整的字符串。您需要在两个命令中分别比较每个单词,然后使用compa从编译器的角度来看:
“abc”、
“a,b,c”和
“a/b/c”之间有什么区别
string literals?无。所有都是string literals。
InStr
无法猜出您的意思。尝试创建一个函数。我将搜索条件和搜索字符串用空格括起来,以提供“整词搜索”。由于逗号,Nee可能有问题,但我相信您可以用s来解释ome错误控制。例如
txtList=Chr(32)和application.trim(替换(“Ho Tee Nee,John”,Chr(44),Chr(32))&Chr(32)