在VBA中比较字符串 [英] Comparing Strings in VBA

查看:938
本文介绍了在VBA中比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基本的编程背景,并且已经很多年了,但是我似乎无法解决这个问题。我在VBA中有一个程序,我需要比较两个字符串。我尝试使用以下方法比较下面的字符串,但无济于事:

I have a basic programming background and have been self sufficient for many years but this problem I can't seem to solve. I have a program in VBA and I need to compare two strings. I have tried using the following methods to compare my strings below but to no avail:

//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。我的字符串的字符长度是否不同?谢谢您的帮助。

VBA for some reason does not recognize these strings as equals. When going through Debugger it shows that StrComp returns 1. Do my strings have different Char lengths? Thanks for any help.

推荐答案

将其发布为答案,因为它不适合注释:

Posting as answer because it doesn't fit in the comments:

我很难相信这样的东西:

I find it hard to believe that something like:

MsgBox "Cat" = "Cat"

在计算机上不会显示 True 。请验证。

Would not display True on your machine. Please verify.

但是,我确实观察到您肯定是错误地使用了 StrComp 函数。

However, I do observe that you are most certainly using StrComp function incorrectly.

正确使用的是 StrComp(string,anotherstring,[比较类型可选])

当您执行 StrComp(A = B,1)时,您实际上是在要求它比较是否是布尔值( A = B 的值为True或False)等于整数 1

When you do StrComp(A=B, 1) you are essentially asking it to compare whether a boolean (A=B will either evaluate to True or False) is equivalent to the integer 1. It is not, nor will it ever be.

当我运行以下代码时,所有四个消息框都会确认每个语句的计算结果为True。

When I run the following code, all four message boxes confirm that each statement evaluates to 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

评论更新

如果使用数组,我看不到任何奇怪的事情,仅供参考。数组中使用的示例数据:

I don't see anything odd happening if I use an array, just FYI. Example data used in the array:

已修改例程以使用数组:

Modified routine to use an array:

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,因此请检查以确保您在比较正确的数组索引。

What I would check is how you're instantiating the array. Range arrays (as per my example) are base 1. If it assigned some other way, it is most likely base 0, so check to make sure that you're comparing the correct array index.

这篇关于在VBA中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆