在VBA中比较字符串

5

我有基本的编程背景,自己解决问题已经多年了,但这个问题我似乎无法解决。我有一个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。我的字符串是否具有不同的字符长度?感谢任何帮助。


我认为您错误地使用了 StrComp。但是其他函数应该可以正常工作(当我测试它们时确实可以工作)。 - David Zemens
我是不是用错了?而且我也不知道该怎么办。如果“D555177”像“D555177”那么……但我什么都没得到。这是因为字符串中有整数吗?这应该没有关系,对吧? - user3768212
看到你的回答了,你肯定是在错误地使用它,将一个布尔值与一个整数进行比较。 - David Zemens
那个最后的语句 If "D555177" Like "D555177" 对我来说也是 True - David Zemens
不要在 StrComp 函数内部放置等号。使用逗号分隔文本字符串。这是错误的:If StrCmp(A=B, 1)=0 Then。应该使用:If StrCmp(A, B, 1)=0 Then - Jon Peltier
显示剩余3条评论
1个回答

17

因内容无法适应评论,我选择以回答的形式发表:

我很难相信像这样的东西:

MsgBox "Cat" = "Cat"

您的机器上不会显示 True。请验证。

然而,我注意到您肯定是在错误地使用 StrComp 函数。

正确的用法是 StrComp(string, anotherstring, [comparison type optional])

当您执行 StrComp(A=B, 1) 时,实际上是要求将一个布尔值(A=B 将评估为 True 或 False)与整数 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开始计数,请确保比较正确的数组索引。


嗯,你说得对。我通过消息框得到了true。也许是因为我使用的数组出了问题。 对于i = 1到8 如果A = B(i) Then... 下一个i - user3768212
是的,StrComp 不应该这样比较。谢谢。 - user3768212
请参阅上面添加的更多信息。也许能让您更接近解决数组的问题(可能性)。 - David Zemens
1
非常感谢你的帮助,David。 - user3768212

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接