user2217713
user2217713

Reputation:

How does AND function work in VBA?

I'm sorry if this is a stupid question, but does the (Excel VBA) AND function checks EVERY single condition in it then proceed, or stops at the first FALSE condition and not checks the other? I'd like to know for optimization purposes and found nothing about it on the web so far.. Thanks in advance!

Example: If InStr(txt, "abc") > 0 And InStr(txt, "xyz") > 0 Then

so if "abc" not found in the txt variable (gives 'false'), then will the macro check the "xyz" too or skip the rest conditions

Upvotes: 3

Views: 695

Answers (2)

user4039065
user4039065

Reputation:

Yes, VBA always tests both conditions in an And statement. This is one reason you cannot test for error values And something else.

For example:

If Not IsError(range("a1").value) And range("a1").value > 0 Then

The above will always fail (type mismatch) when encountering a worksheet error value in a cell (e.g. #N/A, #DIV/0!, etc) since it will still attempt to see if an error value is greater than zero.

If Not IsError(range("a1").value) Then
     If range("a1").value > 0 Then

The above will not fail when encountering an error value in a cell since the error is detected by the first If statement and the second is never reached.

In your case, both abc and xyz must be within the txt string or the statement fails.

Upvotes: 1

Gary's Student
Gary's Student

Reputation: 96753

It appears that VBA keeps on going:

Sub ANDTest()
    If f1() And f2() Then MsgBox "X"
End Sub

Public Function f1() As Boolean
    f1 = False
End Function

Public Function f2() As Boolean
    MsgBox "in f2"
    f2 = False
End Function

enter image description here

Upvotes: 4

Related Questions