结合两个if语句' .second取决于第一个

时间:2016-12-26 12:29:51

标签: vba excel-vba if-statement excel

第二个'如果'只有在第一个语句之后才能出现,所以不会出现运行时错误 - 因为" el_rule"有时候什么都没有.. 所以我不能用 AND 将它们放在同一个语句中。 但在两个' if声明'我希望如果其中一个if语句不会发生同样的代码行将运行(否则)...是我唯一的选择就是只写两次? 喜欢下面的代码?谢谢你的帮助!

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

2 个答案:

答案 0 :(得分:1)

我不太关注(因为我不知道el_rule是什么),但VBA并没有短路其布尔运算符,例如{{1} }。因此,嵌套And语句在VBA中比在其他语言中更常见。如果If有时候什么都没有,那么您需要拥有如下代码:

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 真的是一个特殊情况,那么你可以简单地编写代码,假设它不是,并使用错误处理来捕获它的时间。

答案 1 :(得分: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
相关问题