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
There is a little known fact (or how I like to refer it, Microsoft's little practical joke..) in vba, that the
If..Then..End If
condition has actually two established forms:You basically mixed up multi-line and single-line syntax into one mush, as per MSDN:
Example of a single-line statement:
and multi-line (what you attempted to do):
So to sum it up, your code threw an error, because the
ElseIf
got evaluated as an<expression>
after theIf..Then
statement, instead to evaluating to a conditional like you intended it to.The
If
statement has two legal syntaxes.Inline:
And block:
So if there's a statement on the same line following the
Then
keyword, VBA parses theIf
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".You need the actions on new lines:
Select Case
would be better here: