VBA: Single line if statement with multiple actions
You absolutely can!
If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File doesn't exist" : Exit Sub
The
If
statement does already support single-line syntax.
In simple terms this means, we can either have:If {boolean-expression} Then {execution} End If
If {boolean-expression} Then {execution}
- Note the lack of
End If
at the second option, as it's fully omitted in single-line syntax - Also keep in mind, the execution block can only contain a single statement
- Note the lack of
Then, further way of concatenating the code together is with the
:
which acts as a new line ↵ in the compiler.This is fairly common practice in variable declaration:
Dim x As Integer: x = 42
Now, let's apply those steps together:
The original code
If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File doesn't exist" Exit Sub End If
Applying the single-line
If
syntaxIf Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File Doesn't Exist" Exit Sub
Use the
:
symbol to putExit Sub
into our single-lineIf
If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File Doesn't Exist" : Exit Sub
In VBA you can execute even more than two lines of code in one, just add :
between one instruction and the other! This is perfectly legal:
If True Then MsgBox "True - Line 1": MsgBox "True - Line 2": Exit Sub