VBA StrComp永远不会返回0

我在使用VBA中的StrComp函数比较两个string时遇到了问题。

 Public Function upStrEQ(ByVal ps1 As String, ByVal ps2 As String) As Boolean upStrEQ = False If StrComp(ps1, ps2, vbTextCompare) = 0 Then upStrEQ = True End If If Len(ps1) = Len(ps2) Then Debug.Print ps1 & vbNewLine & ps2 & vbNewLine & upStrEQ End If End Function 

debugging输出:

 Technischer Name Technischer Name Falsch 

正如你所看到的,两个string具有相同的长度和相同的文本,但是upStrEQFalseStrComp没有返回0。

你能帮忙的话,我会很高兴。 谢谢。

更新:由于传递给函数的string之一是在我制作示例文档之前从单元格中读取的,所以您可以重现我的错误: https : //www.dropbox.com/s/6yh6d4h8zxz533a/strcompareTest.xlsm?dl= 0

StrComp()作品相当不错。 问题是你的input,可能你有一个隐藏的空间或一个新的线。

像这样testing你的代码:

 Public Function upStrEQ(ByVal ps1 As String, ByVal ps2 As String) As Boolean If StrComp(ps1, ps2, vbTextCompare) = 0 Then upStrEQ = True End If If Len(ps1) = Len(ps2) Then Debug.Print ps1 & vbNewLine & ps2 & vbNewLine & upStrEQ End If End Function Public Sub TestMe() Debug.Print upStrEQ("a", "a") End Sub 

此外,布尔函数的默认值为false,因此您不需要在开始时进行设置。

为了清理一下你的input,只有字母和数字,你可以使用一个自定义的RegEx函数。 因此,像这样的东西总是会返回字母和数字:

 Public Function removeInvisibleThings(s As String) As String Dim regEx As Object Dim inputMatches As Object Dim regExString As String Set regEx = CreateObject("VBScript.RegExp") With regEx .pattern = "[^a-zA-Z0-9]" .IgnoreCase = True .Global = True Set inputMatches = .Execute(s) If regEx.test(s) Then removeInvisibleThings = .Replace(s, vbNullString) Else removeInvisibleThings = s End If End With End Function Public Sub TestMe() Debug.Print removeInvisibleThings("aa1 Abc 67 ( *^ 45 ") Debug.Print removeInvisibleThings("aa1 ???!") Debug.Print removeInvisibleThings(" aa1 Abc 1267 ( *^ 45 ") End Sub 

在你的代码中,当你将参数ps1ps2传递给upStrEQ时使用它。