Home » excel » excel – Runtime Error 438 in a For Loop checking Userform Control Values

excel – Runtime Error 438 in a For Loop checking Userform Control Values

Posted by: admin April 23, 2020 Leave a comment


I have a UserForm with 132 Control objects on it. The user fills out the form, then clicks the Confirm button to run a macro that uses the submitted information to make decisions. Image below. I wrote an If statement that checks: If no name was entered at the top, then don’t run the macro; If no checkboxes were checked, then don’t run the macro. I found that the If statement does its job in almost all combinations of checked and unchecked boxes; if it finds any one checkbox checked, then it ends for For Loop and carries on with the macro.

Here is a link to an image of my userform:


Here is the quality gate If statement, the asterisked** Line is highlighted when I get the error:

    Dim cCont As Control
    Dim datacheck As Boolean
    datacheck = False
    If ProductName.Value <> "" Then
        For Each cCont In AddNewPage.Controls
            **If TypeName(cCont) = "CheckBox" And cCont.Value = True Then**
                datacheck = True
                Exit For
            End If
        Next cCont
    End If

   If datacheck = True Then
     'very long, hopefully unrelated macro
        MsgBox ("Please name the part, then click at least one" & Chr(13) & "checkbox. These are _
           the parameters to be audited.")
   End If

The problem is that if I check only checkboxes from the group of three at the bottom, I get a Runtime Error 438. I do not get an error if I only check boxes from the top group, or if I check boxes from both the top and bottom groups, but not if I only check boxes from the bottom group.

I cannot identify the difference between the checkboxes at the top and the checkboxes at the bottom. The properties all seem to be the same, so I don’t know why one checkbox would throw an error and the other would not.

How to&Answers:
If TypeName(cCont) = "CheckBox" And cCont.Value = True Then

The problem is that VBA’s And operator isn’t short-circuiting, so both conditions are systematically evaluated for every cCont, which presumably includes Label controls that don’t have a Value property.

You can nest the conditions to achieve the short-circuiting behavior the AndAlso operator would have in VB.NET:

If TypeName(cCont) = "CheckBox" Then
    'we're looking at a CheckBox control
    If cCont.Value Then
    End If
End If