Search code examples
excelvbadivide-by-zero

Or operator in if statement not working as intended


When I use the following code it works fine:

If xMin <> 0 Then
    If xMax <> 0 Then
        If xMax / xMin > 2 Then
            'some code
        End If
    End If
End If

But I want to use only one if statement to avoid division errors, however it gives me a Run-time error '11': Division by zero:

If xMin <> 0 Or xMax <> 0 Then
    If xMax / xMin > 2 Then
        'some code
    End If
End If

(If I can manage to make the above code work), I plan to do it like:

If (xMin <> 0 Or xMax <> 0) And (xMax / xMin > 2) Then
    'some code
End If

What is the reason behind this and how can I make it work in one if statement?


Solution

  • You're out of luck.

    VBA does not implement a short-circuited And, unlike C, C++, Java, &c. It evaluates every term in the expression even if the result is already known. In your case that means that xMax / xMin is evaluated even if xMin is 0.

    So you need to write it as

    If xMin <> 0 And xMax <> 0 Then
        If xMax / xMin > 2 Then
            'some code
        End If
    End If
    

    Note that I've fixed a typo in your conditional: you need an And in place of your Or.