使用复选框隐藏和取消隐藏行的VBA代码

时间:2019-05-14 08:22:41

标签: excel vba

enter image description here {由TOM解决-请参阅ActiveX控件}我有两个按钮(按钮1和按钮2)用于隐藏和取消隐藏在另一张工作簿中包含特定单词“石油”的行(如果我单击按钮1所有包含“石油”的行将隐藏,如果我单击按钮2,则所有包含“石油”的行都将取消隐藏)

我的疑问是,我可以使用一个复选框而不是两个按钮来运行此vba代码吗(想法是,如果我选中了该复选框,那么如果未选中该复选框,则该行应隐藏并取消隐藏。

“用于行隐藏”

Sub Button1_Click()
Dim sht As Worksheet
Application.ScreenUpdating = False
For Each sht In Worksheets
    beginRow = 2
    endRow = 1000
    chkCol = 12
    For RowCnt = beginRow To endRow
        If sht.Cells(RowCnt, chkCol).Value = "Petroleum" Then
            sht.Cells(RowCnt, chkCol).EntireRow.Hidden = True

        End If
    Next RowCnt
Next sht
Application.ScreenUpdating = True
End Sub

“取消隐藏行”

Sub Button2_Click()
Dim sht As Worksheet
Application.ScreenUpdating = False
For Each sht In Worksheets
    beginRow = 2
    endRow = 1000
    chkCol = 12
    For RowCnt = beginRow To endRow
        If sht.Cells(RowCnt, chkCol).Value = "Petroleum" Then
            sht.Cells(RowCnt, chkCol).EntireRow.Hidden = False

        End If
    Next RowCnt
Next sht
Application.ScreenUpdating = True
End Sub

'根据汤姆的建议,我已按照以下内容修改了代码(这对我有用)

Private Sub CheckBox13_Click()
    Dim sht As Worksheet

    Application.ScreenUpdating = False
    For Each sht In Worksheets
        beginRow = 2
        endRow = 1000
        chkCol = 12
        For RowCnt = beginRow To endRow
            If sht.Cells(RowCnt, chkCol).Value = "Petroleum" Then

                sht.Cells(RowCnt, chkCol).EntireRow.Hidden = CheckBox13.Value
            End If
        Next RowCnt
    Next sht
    Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:1)

您还可以在复选框上使用onclick事件,如下所示:

Private Sub CheckBox1_Click()
    If CheckBox1.Value = True Then
       ' hide rows
    Else
        ' unhide rows
    End If
End Sub

祝你好运

答案 1 :(得分:0)

对于Form控件,您可以使用以下命令通过一个按钮完成操作

Sub Button1_Click()
    Dim sht As Worksheet
    Dim chkBox As CheckBox

    Set chkBox = Application.Caller

    Application.ScreenUpdating = False
    For Each sht In Worksheets
        beginRow = 2
        endRow = 1000
        chkCol = 12
        For RowCnt = beginRow To endRow
            If sht.Cells(RowCnt, chkCol).Value = "Petroleum" Then
                sht.Cells(RowCnt, chkCol).EntireRow.Hidden = IIf(chkBox.Value = 1, True, False)
            End If
        Next RowCnt
    Next sht
    Application.ScreenUpdating = True
End Sub

对于ActiveX,您也可以使用

Private Sub CheckBox13_Click()
    Dim sht As Worksheet

    Application.ScreenUpdating = False
    For Each sht In Worksheets
        beginRow = 2
        endRow = 1000
        chkCol = 12
        For RowCnt = beginRow To endRow
            If sht.Cells(RowCnt, chkCol).Value = "Petroleum" Then

                sht.Cells(RowCnt, chkCol).EntireRow.Hidden = CheckBox13.Value
            End If
        Next RowCnt
    Next sht
    Application.ScreenUpdating = True
End Sub