我有基本的编程背景,并且已经很多年了,但是这个问题我似乎无法解决。我在VBA中有一个程序,我需要比较两个字符串。我尝试使用以下方法比较下面的字符串,但无济于事:
//Assume Cells(1, 1).Value = "Cat"
Dim A As String, B As String
A="Cat"
B=Cell(1, 1).Value
If A=B Then...
If A Like B Then...
If StrCmp(A=B, 1)=0 Then...
I've even tried inputting the Strings straight into the code to see if it would work:
If "Cat" = "Cat" Then...
If "Cat" Like "Cat" Then...
If StrCmp("Cat" = "Cat", 1) Then...
VBA由于某些原因无法将这些字符串识别为相等。通过调试程序时,它表明StrComp返回1。我的字符串具有不同的Char长度吗?谢谢你的帮助。
发布为答案,因为它不适合评论:
我发现很难相信这样的东西:
MsgBox "Cat" = "Cat"
无法True
在您的机器上显示。请验证。
但是,我确实发现您肯定会StrComp
错误地使用函数。
正确的用法是 StrComp(string, anotherstring, [comparison type optional])
当您执行此操作时,StrComp(A=B, 1)
您实际上是在要求它比较布尔值(A=B
将评估为True还是False)是否等于integer 1
。不是,也永远不会。
当我运行以下代码时,所有四个消息框都会确认每个语句的评估结果为True。
Sub CompareStrings()
Dim A As String, B As String
A = "Cat"
B = Cells(1, 1).Value
MsgBox A = B
MsgBox A Like B
MsgBox StrComp(A, B) = 0
MsgBox "Cat" = "Cat"
End Sub
来自评论的更新
如果使用数组,则仅供参考,我看不到任何奇怪的事情发生。数组中使用的示例数据:
修改例程以使用数组:
Sub CompareStrings()
Dim A As String, B() As Variant
A = "Cat"
B = Application.Transpose(Range("A1:A8").Value)
For i = 1 To 8
MsgBox A = B(i)
MsgBox A Like B(i)
MsgBox StrComp(A, B(i)) = 0
MsgBox "Cat" = B(i)
Next
End Sub
我要检查的是如何实例化数组。范围数组(以我的示例为例)为基数1。如果以其他方式分配,则很有可能是基数0,因此请检查以确保您在比较正确的数组索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句