簡體   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