2013-07-09 50 views
7

我正在寫在VBA條件語句像VBA相當於SQL「在」功能

if(userID = 1 or userID = 2 or userID = 3 or userID = 4) then 
... 

我在想,如果有這樣做更快,更清潔的方式。像

if(userID in (1,2,3,4)) then 
... 

感謝

+0

? – 2013-07-09 16:45:26

+0

@mehow較少的字符。我的清單將有少於10個數字進行檢查,因此方法之間的性能差異應該可以忽略不計。 – Ben

回答

10

另一種方法是:

select case userID 
    case 1,2,3,4,5,6 
     ' do something 
end select 

它傳達很好的意義if ... then ... else構造。

4

東西,你可以使用Application.Match功能的陣列上:

If Not IsError(Application.Match(userID, Split("1,2,3,4",","))) Then... 
+1

在這種用法中'IsError'是否需要'()'? – Gaffi

+0

是的,它的確如此。接得好。我修改了。 –

5

另一種方式

If UBound(Filter(Array(1, 2, 3, 4, 5, 6), UserID)) > -1 Then 

過濾器返回帶有匹配的陣列。如果沒有匹配,則ubound = -1。

0

CW因爲這符合假設的例子,但不可能是真正的使用情況。但是,Like是一個很好的關鍵字。

If userID Like "[1-6]" Then 

這對單個數字檢查是可以的,但不是現實世界的多字符用戶ID。

userID = 1 
If userID Like "[1-6]" Then ' result is True 

userID = 11 
If userID Like "[1-6]" Then ' result is False 
在更快的較少的字符或代碼的效率方面