vba 如何检查 IF 语句中的值列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32503099/
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
How to check against a list of values in an IF statement?
提问by horace_vr
I am trying to write an IF statement like this:
我正在尝试编写这样的 IF 语句:
if var [is any of 1,4,5,6,12] then do stuff
But I don't know the syntax for this in VBA, other than:
但我不知道 VBA 中的语法,除了:
if var=1 or var=4 or var=5...
which seems a bit clumsy. Is there a different way?
这似乎有点笨拙。有不同的方法吗?
回答by psychicebola
You can use a Select Casestatement:
您可以使用Select Case语句:
select case var
case 1,4,5,6,12
'do something
case else
'alternative
end select
回答by SeanS
You could make a list of numbers, and then in a for-loop to compare these:
您可以制作一个数字列表,然后在 for 循环中比较这些:
dim newNumber as Integer
dim compareList as new List Of(int)
for count as integer = 0 to compareList.count - 1
if newNumber = compareList(nCount)
'Do Stuff
end if
next
This is a simple way of doing that I like to do, but may get performance intensive if your lists are really large/you want to do a lot of code in the "if" loop.
这是我喜欢做的一种简单方法,但如果您的列表非常大/您想在“if”循环中执行大量代码,则可能会占用大量性能。
回答by William Bell
I'm a bit late to the 'party' but how about:
我参加“派对”有点晚了,但是怎么样:
If InStr(1, ",1,5,8", "," & lVal1, vbTextCompare) > 0 Then
to check if 'lVal1' to equal to 1, 5 or 8.
检查“lVal1”是否等于 1、5 或 8。
And
和
If InStr(1, ",6,8,10,12", "," & lVal2, vbTextCompare) = 0 Then
to check that 'lVal2' is not equal to 6, 8, 10, 12.
检查 'lVal2' 不等于 6、8、10、12。
The comma delimiters are important because, without them, in the first example, '15' or '58' or '158' would all be matched if 'lVal' was able to take one of those values.
逗号分隔符很重要,因为如果没有它们,在第一个示例中,如果 'lVal' 能够采用这些值中的一个,'15' 或 '58' 或 '158' 将全部匹配。
You will need to pay attention to the delimiter that you use if there was likely to be any ambiguity with the value being checked for.
如果要检查的值可能存在任何歧义,则需要注意所使用的分隔符。
Likewise, using your knowledge of the range of values that will be encountered, the clunkiness of the leading delimiter in the first string and concatenating the delimiter to the front of the search value, could be removed.
同样,使用您对将遇到的值范围的了解,可以删除第一个字符串中前导分隔符的笨拙以及将分隔符连接到搜索值的前面。

