vba 比较两个字符串变量忽略大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19098977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:34:00  来源:igfitidea点击:

compare two string variables ignoring case

excelvbaexcel-vba

提问by user2385809

I need to compare 2 variable in an If statement but i still want it to refurn true if everything is the same except the cases. I know can't write this but here is a sense of what I am looking to do:

我需要在 If 语句中比较 2 个变量,但我仍然希望它返回 true,如果除情况外一切都相同。我知道不能写这个,但这是我想要做的事情的感觉:

If (str1=str2 matchcase:=false) then

Any ideas? Thanks

有任何想法吗?谢谢

回答by mr.Reband

If (lcase(str1)=lcase(str2)) then

If (lcase(str1)=lcase(str2)) then

回答by Santosh

Though i prefer @mr.Reband answer but still you may refer this alternative which uses StrCompfunction.

虽然我更喜欢@mr.Reband 答案,但您仍然可以参考这个使用StrComp函数的替代方案。

Sub test()

Dim str1 As String
Dim str2 As String

str1 = "test"
str2 = "Test"

MsgBox StrComp(str1, str2, vbTextCompare)


'Return Values
'
'The StrComp function has the following return values:
'
'If StrComp returns
'string1 is less than string2 -1
'string1 is equal to string2 0
'string1 is greater than string2 1
'string1 or string2 is Null Null

End Sub

回答by Steve

If you are looking for the fastest, you'll want to use StrComp()

如果您正在寻找最快的,您将需要使用 StrComp()

StrComp will do several tests to avoid having to actually compare the string or whole string that makes it faster when strings differ. If you do expect a lot of common values, you may avoid StrComp but for the most part it is faster.

StrComp 将进行多项测试,以避免在字符串不同时实际比较字符串或整个字符串,从而使其更快。如果您确实期望有很多通用值,则可以避免使用 StrComp,但在大多数情况下它会更快。

100M comparisons with same phrase but different case:
LCase = 20 seconds
StrComp = 23 seconds *This is a rare case

100M comparisons with different phrase but same length
LCase = 20 seconds
StrComp = 9 seconds

100M comparisons with different phrase and different length
LCase = 25 seconds
StrComp = 9 seconds

NOTE: Lengths of strings will vary the results. For example, on the last test, LCase took longer than the other tests because I doubled the length of one of the strings. This slowed LCase down but not StrComp.

注意:字符串的长度会改变结果。例如,在上次测试中,LCase 比其他测试花费的时间更长,因为我将其中一个字符串的长度加倍。这减慢了 LCase 但不会减慢 StrComp。

NOTE2: LCase and UCase had similar results.

注 2:LCase 和 UCase 的结果相似。