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:

    1. If {boolean-expression} Then
         {execution}
      End If
      
    2. 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

  • 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:

  1. The original code

    If Dir("C:\file.txt", vbDirectory) = "" Then 
       MsgBox "File doesn't exist"
       Exit Sub
    End If
    
  2. Applying the single-line If syntax

    If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File Doesn't Exist"
    Exit Sub
    
  3. Use the : symbol to put Exit Sub into our single-line If

    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

Tags:

Excel

Vba