繁体   English   中英

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

[英]Vba code for hide and unhide rows by using a checkbox

在此处输入图像描述 {由TOM解决,请参考ActiveX控件}我有两个按钮(按钮1和按钮2)隐藏和取消隐藏在另一张工作簿中包含特定单词“石油”的行(如果我单击按钮1,则所有包含“石油”的行将隐藏,如果单击按钮2,则所有包含“石油”的行都将取消隐藏)

我的疑问是,我可以使用ONE复选框而不是两个按钮来运行此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

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

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

祝好运

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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