VBA 等效于 SQL 'in' 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17553700/
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
VBA equivalent to SQL 'in' function
提问by Ben
I'm writing a conditional statement in vba like
我正在用 vba 写一个条件语句,比如
if(userID = 1 or userID = 2 or userID = 3 or userID = 4) then
...
I was wondering if there's a quicker, cleaner way to do this. Something like
我想知道是否有更快,更清洁的方法来做到这一点。就像是
if(userID in (1,2,3,4)) then
...
Thanks
谢谢
回答by MicSim
An alternative would be:
另一种选择是:
select case userID
case 1,2,3,4,5,6
' do something
end select
It conveys very good the meaning of the if ... then ... else
construct.
它很好地传达了if ... then ... else
构造的含义。
回答by Dick Kusleika
Another way
其它的办法
If UBound(Filter(Array(1, 2, 3, 4, 5, 6), UserID)) > -1 Then
Filter returns an array with the match. If there's no match, ubound = -1.
过滤器返回一个匹配的数组。如果没有匹配项,则 ubound = -1。
回答by David Zemens
You can use the Application.Match
function on an array:
您可以Application.Match
在数组上使用该函数:
If Not IsError(Application.Match(userID, Split("1,2,3,4",","))) Then...
回答by Gaffi
CWbecause this matches the hypothetical example, but not likely a real use situation. However, Like
is a good keyword to know.
CW,因为这与假设示例相符,但不太可能是实际使用情况。但是,Like
是一个很好的关键字。
If userID Like "[1-6]" Then
This is ok for single digit checks, but not real world multi-character user IDs.
这适用于单个数字检查,但不适用于现实世界的多字符用户 ID。
i.e.
IE
userID = 1
If userID Like "[1-6]" Then ' result is True
but
但
userID = 11
If userID Like "[1-6]" Then ' result is False