I really should be able to google this, but I can't find what I wanna know about.
I want to check if a file exists. If not, a MessageBox should pop up and VBA should exit the sub.
If Dir("C:\file.txt", vbDirectory) = "" Then
MsgBox "File doesn't exist"
Exit Sub
End If
It works, I just wanna know if you can you do this in a single line statement? Does VBA allow this when more than one thing is supposed to happen (like it is the case here)? This code doesn't work (syntax error):
If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File doesn't exist" And Exit Sub
First, start the IF statement with the “IF” keyword. After that, specify the first condition that you want to test. Next, use the OR keyword to specify the second condition. In the end, specify the second condition that you want to test.
There can be multiple Else If…Then clauses in a VBA if statement, as long as each Else If … criteria is mutually exclusive from other Else If or If criteria. End If should close the last Else If…Then statement. In the above example, if Cell A5 is 91, then Cell A6 will be set to Decent Performance.
In case you have multiple conditions to check, you can use: Multiple IF conditions. If Then Else statement.
AutoCAD to Excel - VBA Programming Hands-On! An If statement followed by one or more ElseIf statements that consists of boolean expressions and then followed by a default else statement, which executes when all the condition becomes false.
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}
End If
at the second option, as it's fully omitted in single-line syntax 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
syntax
If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File Doesn't Exist"
Exit Sub
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With