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

查看:27
本文介绍了在 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 出于某种原因不能将这些字符串识别为相等.通过 Debugger 时,它显示 StrComp 返回 1.我的字符串是否有不同的 Char 长度?感谢您的帮助.

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:

修改例程以使用数组:

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天全站免登陆