我正在寻找一种比较VBA中两个字符串变量的方法。我正在使用的当前语句(未产生所需结果)是:
If Variable1 = Variable2 Then...
我有一个VBA宏,它在我的代码的第一部分中分配了两个变量:
Dim Variable1 as String Variable1 = Left(Range("$F$3").Value, 4)
Dim Variable2 as String Variable2 = ("SheetName.B15")
我已尝试使用以下语句,但仍无法正常工作:
If Variable1 Like Variable2 Then...
以前,该声明正在使用与第一个变量的字符串比较,但它要求我硬编码" ABC"串。它看起来像下面的声明:
If Variable1 = "ABC" Then...
是否有人知道比较两个字符串变量的语句的语法,或者可以推荐一种方法来比较它们并返回二进制结果,然后我可以比较它?
谢谢!
在Windows 8上运行VBA for Excel 2013
答案 0 :(得分:2)
您可以使用StrComp
Sub compare()
MsgBox StrComp("Stack", "stack") 'alerts -1
End Sub
Sub compare()
MsgBox StrComp("Stack", "stack", 1) 'Compare as text while ignoring case
End Sub
第一个是区分大小写的,第二个不是,当然你可以用变量替换硬编码的值
答案 1 :(得分:0)
以下是解决方案:
我没有正确分配Variable2,因此,该功能没有产生所需的结果。感谢大家的贡献,通过回复 - 这就是我们想出的:
要比较现有子中的两个字符串变量,请使用:
If Variable1 = Variable 2 Then...
要比较它自己的子中的两个字符串变量,请使用:
Sub compare()
MsgBox StrComp("Stack", "stack") 'alerts -1
End Sub
Sub compare()
MsgBox StrComp("Stack", "stack", 1) 'Compare as text while ignoring case
End Sub