嵌套 If then Else 语句的 VBA 语法是否正确?编译错误:Else without If

问题描述 投票:0回答:1

我对VBA还是个菜鸟,但已经取得了一些进步。 我当前的障碍导致编译错误“Else without If”。 在检查我的代码时,我相信我已经正确嵌套了 If then-ElseEnd If 条件。

If Not var1 Is Nothing Then
  For i = 1 To var2 Do
    Copy-Paste some records
    If Condition A Then
      Copy-Paste some other records
    Else
      MsgBox "False Condition A"
    End If
  i = i + 1
Else
  MsgBox "False Conditon1"
End If

VBA 编译器选择 Else 语句作为外部 If Then 语句,并出现“Else without If”作为编译错误。不知道For循环是否不允许? 我相信我已经正确定义了嵌套结构。

我尝试过 ElseIf 但这似乎并不适用。 有一个外部条件,有两个预期条件。 如果为 True,则在代码的 True 部分内,存在一个带有两个预期条件的内部条件(与外部条件不同的变量)。 当该条件为 false 时,退出内部 If 直到外部 If 为 false,然后也退出。

if-statement nested
1个回答
0
投票

虽然我同意错误消息可能更清晰,但您必须记住,编译器报告它们遇到的第一个错误,而不是实际的根本原因。外面的 If then else 就可以了。

在这种情况下,问题是 for 循环不完整(缺少

next i
),因此根本不希望看到
else
语句。这个非常简单的改变应该可以让它发挥作用。始终查看错误消息声称出现问题的位置之前(有时可能要追溯到很久以前)。

If Not var1 Is Nothing Then
  For i = 1 To var2 Do
     Copy-Paste some records
     If Condition A Then
        Copy-Paste some other records
     Else
        MsgBox "False Condition A"
     End If
  Next i   '' This is the  missing like the compiler has complained about
  '''' **WRONG** very very bad practice to alter a for loop variable  i = i + 1
Else
   MsgBox "False Conditon1"
End If
© www.soinside.com 2019 - 2024. All rights reserved.