Search code examples
vbaor-operatorand-operator

And/Or combination in VBA


I am confused on how 'and' 'or' statements work together. I am trying to make a (something Or something) statement work as part of an 'and' statement but cannot figure out the logic The problem is illustrated by the following two code blocks. The first one works fine..the second fails with Run time error 438: "Object doesn't support this property or method". The error refers to the "If j.Enabled..." line. In my opinion both should run..can anyone elaborate on why this isn't so?

Code block 1 (runs)

Private Sub Fini_cbn_Click()
Dim j As Control
For Each j In Controls
    If j.Enabled = True And j.Tag = "4" Then
        If j.Value = "<NA>" Or j.Value = "" Then
            j.BackColor = &HFFFF&
            Else
            j.BackColor = &H80000005
        End If
    End If
Next j
End Sub

Code block 2 (fails)

Private Sub Fini_cbn_Click()
Dim j As Control
For Each j In Controls
    If j.Enabled = True And j.Tag = "4" And (j.Value = "<NA>" Or j.Value = "") Then
        j.BackColor = &HFFFF&
        Else
        j.BackColor = &H80000005
    End If
Next j
End Sub

Solution

  • VBA doesn't short circuit. This means that the entire expression gets evaluated everytime.

    So here

    If j.Enabled = True And j.Tag = "4" Then
        If j.Value = "<NA>" Or j.Value = "" Then
    

    j.Value only gets evaluated IF j.Enabled And j.Tag = "4" and everything is fine.

    But here

    If j.Enabled = True And j.Tag = "4" And (j.Value = "<NA>" Or j.Value = "") Then
    

    The entire statement gets evaluated "at once". So, there must be a control in your collection that does not have a Value property. Since the property doesn't exist, it can't evaluate the statement.