简体   繁体   中英

Excel VBA code to update the hide/unhide rows functions when a new row is added within the range wanted to be hidden

I currently have a code as follows to hide a range of cells when an activeX checkbox is clicked:

Version 1:

Private Sub CheckBox1_Click()

    If CheckBox1.Value = True Then

    Rows("14:30").Hidden = False

    Else

    Rows("14:30").Hidden = True

    End If

End Sub

Private Sub CheckBox2_Click()

    If CheckBox2.Value = True Then

    Rows("32:38").Hidden = False

    Else

    Rows("32:38").Hidden = True

    End If

End Sub

Private Sub CheckBox3_Click()

    If CheckBox3.Value = True Then

    Rows("40:54").Hidden = False

    Else

    Rows("40:54").Hidden = True

    End If

End Sub

Version 2:

Private Sub CheckBox1_Click()

    [14:30].EntireRow.Hidden = Not CheckBox1

End Sub

Private Sub CheckBox2_Click()

    [32:38].EntireRow.Hidden = Not CheckBox2

End Sub

Private Sub CheckBox3_Click()

    [40:54].EntireRow.Hidden = Not CheckBox3

End Sub

THE PROBLEM:

Both versions work fine BUT the problem is that when a new row is added within the ranges specified, the row specifications obviously do not update as they are not variables.

NOTE : There are more than 3 ActiveX checkboxes. I've got about 19.

QUESTION

I know the ranges need to be put to an integer or a variable but I am only new to VBA and not even a programmer (studied a few programming applications in college 4 years ago so can read code a bit) so I have no idea how to do it. Currently working on automating an excel file at work and WOULD LOVE YOUR HELP PLEASEEEE! I have been struggling for days on this :(

Excel file looks like this:

剪辑1

剪辑2

Thank you in advance!!

You need to dynamically determine the starting row and end row for each section. This should work for the top A - General section.

Option Explicit

Private Sub CheckBox1_Click()

    Dim m1 As Variant, m2 As Variant

    m1 = Application.Match("A -*", Columns(1), 0)
    m2 = Application.Match("B -*", Columns(1), 0)

    If IsError(m1) Or IsError(m2) Then Exit Sub

    With Range(Cells(m1 + 1, "A"), Cells(m2 - 1, "A"))
        .EntireRow.Hidden = Not CheckBox1.Value
    End With

End Sub

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM