Skip to Main Content

Evaluating Multiple Expressions in an If Statement

It is common to have multiple expressions in an If statement using logical operators And, Or, etc. Remember that every expression in the If statement will always be evaluated, even if a previous expression renders the entire statement False. This could cause an unexpected error in certain situations.

'
' Even if x=0 the second expression will be evaluated
' raising a divide by 0 error.
'
If (x > 0) And (y / x > 1) Then
        ' Do something here
    End If

'
' Separate the expressions to avoid a divide by 0 error.
'
    If (x > 0) Then
        If (y / x > 1) Then
            ' Do something here
        End If
    End If
Leave a Reply

Your email address will not be published. Required fields are marked *