Search code examples
if-statementnested

Correct VBA Syntax for Nested If Then Else Statements? Compile error: Else without If


I am quite the rookie to VBA, but have made some progress. My current roadblock is resulting in a compile error, "Else without If". In reviewing my code, I believe I have correctly nested the If Then-ElseEnd If conditions.

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

The VBA Compiler selects the Else statement for the outer If Then statement with "Else without If" as the compile error. I'm not sure if the For loop is not allowed? I believe I have the nested structure defined correctly.

I have tried ElseIf but that doesn't really seem to apply. There is an outer condition, with two expected conditions. If True, within the True section of code, there is an inner condition (different variables than outer condition) with two expected conditions. When that condition is false, exit the inner If until the outer If is false, and then exit as well.


Solution

  • Whilst I agree the error message could be much clearer you have to bear in mind that compilers report the first error that they run into rather than the actual root cause. The outer If then else is fine.

    In this case the problem is that the for loop is incomplete (missing next i) so it wasn't expecting to see an else statement at all. This very simple change should make it work. Always look just prior to where an error message claims that something is wrong (sometimes it can be a long way further back).

    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