Trevesy
Trevesy

Reputation: 117

VB - Unchecking Check Boxes in a Group Box: Answer doesn't work

I found a possible answer to my question on how to do this here

However the code from that question:

Sub UnCheckBoxes()
Dim ChkBox As CheckBox = Nothing
    ' to unchecked all
    For Each ChkBox As Object In Worksheets("Check sheet").Report_Checks.Controls
        If TypeOf xObject Is CheckBox Then
            ChkBox = xObject
            ChkBox.Checked = False
        End If
    Next
End Sub

Produces a 'Compile error: syntax error'. Any help appreciated

Upvotes: 0

Views: 90

Answers (2)

A Friend
A Friend

Reputation: 2750

Here is a solution which uses OfType to remove the need for checking the object type each time

For Each ChkBox As CheckBox In Worksheets("Check sheet").Report_Checks.Controls.OfType(Of CheckBox)
    ChkBox.Checked = False
Next

Upvotes: 3

aaroncatlin
aaroncatlin

Reputation: 3271

As per my comment. Switch your code to:

Sub UnCheckBoxes()
    Dim ChkBox As CheckBox = Nothing
    ' to unchecked all
    For Each xObject As Object In Worksheets("Check sheet").Report_Checks.Controls
        If TypeOf xObject Is CheckBox Then
            ChkBox = xObject
            ChkBox.Checked = False
        End If
    Next
End Sub

The xObject object is used as a generic class to loop through all of your controls in Report_Checks. The If statement then checks if xObject is of type CheckBox. ChkBox is then set to xObject so that you can access it's CheckBox properties and assign .Checked = False

Upvotes: 3

Related Questions