All the "ElseIf [condition] Then [action]" statements are on one line without any issue though. This seems inconsistent. Or am I still missing something?
VBA compile errors that make no sense
Can someone explain to me why the VBA compiler gets upset in these two situations? The fixes look like they should be completely unnecessary.
With parentheses, it expects an expression, which is not applicable here since the default message box doesn't return a value. It's unintuitive since not using/needing parenthesis around function arguments is contrary to coding norms.
The compile error goes away if I put MsgBox("Select Employee") on a newline. It's not an issue with the initial If statement, which runs fine on its own. And I thought VBA doesn't have meaningful indentation, so why does a newline affect the following Elseif?
Microsoft 365 and Office | Access | For business | Windows
Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.
17 answers
Sort by: Most helpful
-
Anonymous
2024-05-17T23:40:55+00:00 -
Anonymous
2024-05-18T11:22:16+00:00 You need to stop thinking of this in terms of lines, but of complete self-contained constructs. As we know, the IF construct can be of two forms, single line or block, and only the latter can include ELSEIF statements. Take the following example:
Let x, y, and z be three constants of which y and z are distinct. Let a, b, and c be three variables, to one of which we want to assign the value of x on the basis of its equality or otherwise with y or z. We can express this in two ways, firstly as a set of independent single line constructs:
IF x = y THEN a = x
IF x = z THEN b = x
IF NOT(x = y OR x = z) THEN c = x
Or as a single block construct:
IF x = y THEN
a = x
ELSEIF x = z THEN
b = x
ELSE
c = x
END IF
We cannot include an ELSEIF statement in the first method, because it is a set of independent single line constructs, not a block construct.
Alternatively we can express the same thing with:
SELECT CASE x
CASE y
a = x
CASE z
b = x
CASE ELSE
c = x
END SELECT
I've used upper case in the above for clarity, to distinguish the keywords from the variables. In VBA the keywords would be in proper case of course.