If Then Statements in VBA

If Then statements in VBA




If Then statements in VBA are one way you can choose on which path the code will run.












The most common for is an If Then block which starts with an If, and ends (on a subsequent line) with an End If, and has, at least, a Then. For example...

If Variable_Stop = True Then
    End 'Terminates the codes execution
End If



Between the If and the Then you put a statement that is to be evaluated. In the above example, we could have used Variable_Stop as our statement without "= True" VBA would have evaluated it the same way. If the statement is True it would enter the block.


Even though it is easier for reading and debugging to use a block, there is a way to do it all on one line... If Variable_Stop = True: Then End ' (No "End If" is used here) If the statement after the If is False code execution would continue after the End If statement. Unless there is an Else keyword between the If and End If, in which case, the statements between the Else and End If are executed.

If MyNum > 5 Then
    YourNum = 100
Else
    YourNum = YourNum + MyNum
End If

You can also use ElseIf clauses to check other conditions if the previous condition was false...





If a > b Then
    MsgBox "a > b"
ElseIf c > a
    MsgBox "c > a"
ElseIf b > c Then
    MsgBox "b > a"
Else
    MsgBox "Else"
End If

You can use as many ElseIf statements as you need. The Else clause is always the last clause before the End If. If you choose to, you can use one line, separating statements with a colon, and no End If isused...

If t = y Then b = c: r = i Else r = y: b = 9





Google


Return from If Then statements in VBA to VBA Code Samples


Return to our Homepage