How does AND function work in VBA?

点点圈 提交于 2020-01-04 02:19:11

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/47620201/how-does-and-function-work-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!