2016-12-26 47 views
0

秒'如果'只能在第一個語句之後出現,所以不會有運行時錯誤 - 這是因爲「el_rule」有時可能是空的。 所以我不能把這兩個在與相同的聲明。 但在'if語句'之後,如果其中一個if語句不會發生(else),那麼我想讓相同的代碼行運行...是我唯一的選擇,它只是寫了兩次? 像下面的代碼?謝謝你的幫助!結合兩個'if語句'.second取決於第一個

If el_rule.Length > 0 Then 
        If LCase(ActiveCell.Offset(0, el_rule.Item(0).Attributes.getNamedItem("column_number").Text).Value) = LCase(el_rule.Item(0).Attributes.getNamedItem("value").Text) Then 
        Set el = xDoc.SelectNodes("/simulator") 

       Else 
        Set el =....... -code first time 
       End If 
else 
        Set el =....... -code second time 
       End If 

回答

1

,你可以使用一個輔助變量Boolean

Dim doIt As Boolean 

If el_rule.Length > 0 Then doIt = LCase(ActiveCell.Offset(0, el_rule.item(0).Attributes.getNamedItem("column_number").Text).Value) = LCase(el_rule.item(0).Attributes.getNamedItem("value").Text) 
If doIt Then 
    Set el = xDoc.SelectNodes("/simulator")  
Else 
    Set el =....... -code only time 
End If 
1

我不太明白(因爲我不知道什麼是el_rule),但VBA沒有它的布爾運算符,如And的短路。因此,嵌套的If語句在VBA中比在其他語言中更常見。如果el_rule是有時什麼也沒有,那麼你就需要有這樣的代碼:

If Not el_rule Is Nothing Then 
    If el_rule.Length > 0 Then 
     'Code in which el_rule is something And with Length > 0 
    End If 
Else 
    'code to handle the case when el_rule is nothing 
End If 

作爲替代,如果是真正的特殊情況爲el_rule是什麼,你可以簡單地編寫假定它的代碼是不是和使用錯誤處理來捕捉時間。

+0

你不能只有一個「結束,如果」 2 if語句... – David

+0

@大衛這僅僅是一個模板。任何需要的結束如果爲內部如果隱含在省略號中的評論''...' –

+0

@大衛我讓模板更清晰一點。 –