Home » excel » excel – Loop Through CheckBox Controls in VBA UserForm

excel – Loop Through CheckBox Controls in VBA UserForm

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a user form in Excel VBA with a check box for each month.

Selecting one or more cause the required month to be shown on the sheet, I copy-pasted the code 12 times and it works but I’m sure there is a better way doing it with a For loop.

This is a part of my code (it goes on 12 times):

    If CheckBox1.Value = True Then
        ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems("1").Visible = True
    Else
       ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems("1").Visible = False
    End If

    If CheckBox2.Value = True Then
        ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems("2").Visible = True
    Else
       ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems("2").Visible = False
    End If

I tried writing:

for i in range 1 to 12

and then writing my code but there seem to be a problem when I put “i” instead of the numbers.

How to&Answers:

Assuming you aren’t using Tristate checkboxes, then the .Value can only be True or False, so we should be able to get away with something like this:

(Assumes your code runs inside the UserForm, so that Controls is directly accessible)

Dim mthIdx as Long
Dim nm as String
Dim c As Control

With ActiveSheet.PivotTables("PivotTable1").PivotFields("month")
    For mthIdx = 1 To 12
        nm = "CheckBox" & mthIdx
        Set c = Controls(nm)
        .PivotItems(mthIdx).Visible = c.Value
    Next
End With

(The With clause isn’t strictly necessary, but it’s usually a good idea to resolve nested COM references as infrequently as possible)

Answer:

Try this ..

Dim i As Integer
Dim sN As String
Dim chx As MSForms.CheckBox
Dim obj As OLEObject

For i = 1 to 12
    sN = format(i) 
    Set obj = OLEObjects("CheckBox" & sN)
    Set chx = obj.Object

    If chx.Value = True Then
        ActiveSheet.PivotTables("PivotTable" & sN).PivotFields("month").PivotItems(sN).Visible = True
    Else
       ActiveSheet.PivotTables("PivotTable" & sN).PivotFields("month").PivotItems(sN).Visible = False
    End If
Next

Answer:

I’ve not checked the code but this should put you along thr right path if it’s not spot on though…

For i = 1 to 12
    If CheckBox(i).Value = True Then
        ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems(i).Visible = True
    Else
       ActiveSheet.PivotTables("PivotTable1").PivotFields("month").PivotItems(i).Visible = False
    End If
Next i