2012-01-11 34 views
1

ex。if語句的最佳做法是超出vb6中的10行延續限制

if condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or _ 
condition or then 
do something 
end if 

說我有比這10個條件,我需要評估更多...難道還有比if語句只是嵌套多套的這些更好的辦法?

+0

你也可以把多個條件上線,但可能傷害可讀性。 – 2012-01-11 21:06:56

回答

3

這裏有一個選項 - 一次做一個測試,跟蹤最終結果爲布爾值。當你全部完成時,只需測試布爾值。

Dim A As Long 
Dim B As Long 
Dim C As Long 
Dim D As Long 

Dim Result As Boolean 

Result = True 
Result = Result And (A > 10) 
Result = Result And (B > 10) 
Result = Result And (C > 10) 
Result = Result And (D > 10) 

If Result Then 
    ' Do "something" here... 
End If 

如果任何A的,B,C,或d是小於10,Result將翻轉到False並且從那時起保持這種方式。如果所有的測試都通過,它只會是True

+0

優雅,我喜歡那樣。謝謝! – 2012-01-11 21:15:35

2

您可以使用Case語句。它比IF更清潔一些:http://msdn.microsoft.com/en-us/library/cy37t14y%28v=vs.80%29.aspx

+0

嗯,這將需要把「做某事」功能之間的每一個。或更新每個標誌。看起來好像比長期嵌套的ifs更多的代碼。 – 2012-01-11 21:13:49

+0

@TonyRaymond這取決於條件是什麼。如果您正在檢查表達式是否與一組值相匹配,則「Select Case」是完美的。例如,要檢查變量'a'是否具有一組值中的一個,請執行以下操作:'選擇案例a:案例1,2,3,4,5,6,7,8,9,10:做一件可以漂亮的東西' – MarkJ 2012-01-12 11:56:55

1
dim Result as boolean 
result = false 
if condition1 then result = true 
elseif condition2 then result = true 
elseif condition3 then result = true 
elseif condition4 then result = true 

if result then debug.print "Success" 

,如果你想使用這裏的條件是不一樣的select語句,然後使用

select case True 
    case A=5,b=10,c="my answer",d=11 
     .... 
end select