2016-12-26 45 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

@大卫我让模板更清晰一点。 –