Home » excel » Excel VBA Macros Using Checkboxes To Hide Rows – If Else Statements

Excel VBA Macros Using Checkboxes To Hide Rows – If Else Statements

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have 60 check boxes on one worksheet. They are form control checkboxes. They all do a similar function which is hide rows. When you click the check box it shows the rows
When unchecked the rows are hidden. Is there an easy if else or case statement I could write for this:

Sub CheckBox1_Click()

    If Range("B4").Value = True Then
        Rows("5:62").EntireRow.Hidden = False
    Else
        Rows("5:62").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox2_Click()

    If Range("B63").Value = True Then
        Rows("64:102").EntireRow.Hidden = False
    Else
        Rows("64:102").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox3_Click()

    If Range("B103").Value = True Then
        Rows("104:129").EntireRow.Hidden = False
    Else
        Rows("104:129").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox4_Click()

    If Range("B130").Value = True Then
        Rows("131:160").EntireRow.Hidden = False
    Else
        Rows("131:160").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox5_Click()

    If Range("B161").Value = True Then
        Rows("162:183").EntireRow.Hidden = False
    Else
        Rows("162:183").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox6_Click()

    If Range("B184").Value = True Then
        Rows("185:222").EntireRow.Hidden = False
    Else
        Rows("185:222").EntireRow.Hidden = True
    End If

End Sub

Sub CheckBox7_Click()

    If Range("B223").Value = True Then
        Rows("224:244").EntireRow.Hidden = False
    Else
        Rows("224:244").EntireRow.Hidden = True
    End If
End Sub

……..etc etc

Also, if I need to add more rows in or delete rows, how would I code that in?

I would appreciate a format that I could use to create my own check boxes in the future without having to manually fix and edit them individually

How to&Answers:

You could use something like this:

Sub CheckBox1_Click()
   HideRows "B63", "64:102"
End Sub


Sub HideRows(controllerRange, rowRange)
   Rows(rowRange).EntireRow.Hidden = Not Range(controllerRange).Value
End Sub

You could also call HideRows directly from the checkbox.

In CheckBox1 assign macro, you would enter the following:

'HideRows "B63","64:102"'

Note: The single quotes MUST be entered as shown.