If/Else Then Do Nothing in Excel VBA
When we don’t want to do anything in an If-then-else statement, believe it or not, we can simply not place any code!
This is the most straightforward way to ‘do nothing’ in VBA. VBA does not have a specific statement that can be used for ‘doing nothing’. Unlike Python, which has a pass statement that can be placed where we do not want to take any action, VBA does not use such a statement.
A slightly more complex solution is needed if by trying to do ‘nothing’ we are actually trying to skip an iteration in a loop.
Example 1: No Code
In this example, we simply do not place any code in the location where we do not want anything to happen. We choose to not do anything if the statement is true, but if the statement is false, then it will print “something will happen because the statement is false.”
Sub No_Code() If 1 = 2 Then Else MsgBox "something will happen because the statement is false.” End If End Sub
Similarly, if we decide to do something only when the statement is true, it would be in the following way:
Sub No_Code() If 1 = 1 Then MsgBox "something will happen because the statement is true.” Else End If End Sub
Example 2: Skip Iteration
In this example, we want to do nothing by skipping an iteration in a loop. We do this by rerouting the flow of the execution of our code to a bookmark that is placed right before the looping keyword.
Let’s assume we are looping x from 1 to 5. We will not do anything if X is less than 3, otherwise, we display a message stating the value of x. The statement ‘i
f X < 3 Then GoTo skipX’ will move the flow of the code to the bookmark
skipX, which is right at the
Next X statement. The same strategy can be used for any other type of loop.
Sub Skip_Iteration() For X = 1 To 5 If X < 3 Then GoTo skipX MsgBox X skipX: Next X End Sub
Doing nothing in VBA is as simple as not writing any code, or re-routing the flow of code so that you skip all the things that otherwise the code would have done.
2 thoughts on “If/Else Then Do Nothing in Excel VBA”