What am I missing in this code: “Else without if error”?

  • A+
Category:Languages

I am trying to run this code which first declares wsD and then WsS depending on a cell in the "Data" tab. I keep getting an

else without if error.

Set wsD = ThisWorkbook.Sheets("Data")      If wsD.Range("C4") = "AL" Then Set wsS = ThisWorkbook.Sheets("AL_Sim")     ElseIf wsD.Range("C4") = "COLL" Then Set wsS = ThisWorkbook.Sheets("COLL_Sim")     ElseIf wsD.Range("C4") = "COMP" Then Set wsS = ThisWorkbook.Sheets("COMP_Sim")     ElseIf wsD.Range("C4") = "GL" Then Set wsS = ThisWorkbook.Sheets("GL_Sim")     ElseIf wsD.Range("C4") = "EPL" Then Set wsS = ThisWorkbook.Sheets("EPL_Sim")     ElseIf wsD.Range("C4") = "LAW" Then Set wsS = ThisWorkbook.Sheets("LAW_Sim")     ElseIf wsD.Range("C4") = "POL" Then Set wsS = ThisWorkbook.Sheets("POL_Sim")      End If Next 

 


The If statement has two legal syntaxes.

Inline:

If {bool-expression} Then {statement} 

And block:

If {bool-expression} Then     {statements} End If 

So if there's a statement on the same line following the Then keyword, VBA parses the If statement as the inline syntax.

Thus, since the statement is complete, the next statement beginning with ElseIf makes no sense to the compiler: there's an "else without if".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: