VBA: 嵌套 With with If 语句

VBA: nested With with If statement

在VBA中是否允许嵌套?如果是,如何与IF语句一起使用?

我将以下嵌套 With 与 If 语句结合使用,编译器给我一条错误消息,提示“End With without With”。

With
If
    With
    End With
Else
    End With   <- End With without With
End If

我把第一个With放在IF语句外面,因为IF语句可以用到它。由于上面的代码不起作用,我尝试了不同的方法。如果我将第一个 With 移动到 IF 语句中,则会收到另一条错误消息。这一次,错误信息是“Else without If”。这让我想知道 VBA.

中是否允许嵌套 With

出现 google 搜索 one hit,这与我的问题不完全相同。

像下面这样尝试

With
  If <Logical Test> Then
    With
      'Your action here
    End With
  Else
      'Your other actions here.
  End If
End With

With End With 结构仅适用于当前作用域。 if else 的范围与 else endif 不同。因此 with 应该包含整个 if 语句或单独出现在每个范围中。

完全有可能将 with end with 嵌套在其他 With End With 结构中。在这种情况下,您必须记住领先的 .指的是当前范围。