Excel VBA 根据单元格颜色隐藏行,如果命令显示 "Yes"

Excel VBA Hide Rows based on cell color and if command says "Yes"

我试图根据两个条件隐藏行:

条件 1:如果单元格 Q3 具有值 "yes" 隐藏符合条件 2

的单元格

条件 2:如果 A 列中的单元格为 RGB 颜色(253、233、217),则隐藏整行。

基本上,我有一个跟踪每天电子邮件计数的天数列表,我想隐藏任何周末,这样它们就不会出现在显示趋势的图表上。我正在愚弄我的上级,所以他们所要做的就是从单元格 Q3 的下拉列表中单击 "Yes" 或 "no" 以隐藏周末行。周末是浅橙色(上面列出的 rgb 代码)。同样重要的是,如果单元格 Q3 状态为 "no",则所有行都将 unhide/remain 取消隐藏。我现在的代码是:

Sub HideRows()
BeginRow = 1
EndRow = 1000
ChkCol = 1
ChkCommCol = 17

For RowCnt = BeginRow To EndRow
    If Cells(RowCnt, ChkCommCol).Value = "Yes" Then
        If Cells(RowCnt, ChkCol) = RGB(253, 233, 217) Then
            Cells(RowCnt, ChkCol).EntireRow.Hidden = True
        Else
            Cells(RowCnt, ChkCol).EntireRow.Hidden = False
    If Cells(RowCnt, ChkCol).EntireRow.Hidden = True Then
        Cells(RowCnt, ChkCol).EntireRow.Unhide = True
    End If
Next RowCnt

End Sub

如果您需要更多信息,请告诉我!非常感谢您的帮助。

首先,您在整个代码中遗漏了一些 End If 语句,我对您的问题进行了一些缩进编辑,以帮助显示这些语句的位置,以后尝试缩进以帮助确保您关闭 LoopsIf 语句。

关于您的 If 语句,您需要检查单元格内部的颜色,而不仅仅是单元格。这是通过语法完成的:

Cells(x, y).Interior.Color = RGB(r, g, b)

试试这个:

Sub HideRows()
BeginRow = 1
EndRow = 1000
ChkCol = 1
ChkCommCol = 17

Application.ScreenUpdating = False 'Speeds up subroutine
Application.Calculation = xlCalculationManual

If Cells(3, ChkCommCol).Value = "Yes" Then 'This line checks that `Q3` is "Yes"
    For RowCnt = BeginRow To EndRow 'This line loops through the rows and hides the weekends
        If Cells(RowCnt, ChkCol).Interior.Color = RGB(253, 233, 217) Then
            Cells(RowCnt, ChkCol).EntireRow.Hidden = True
        End If
    Next RowCnt
Else
    Rows.EntireRow.Hidden = False 'This line unhides all rows in the activesheet if `Q3` isn't "Yes"
End If

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

您可以在任何模块代码窗格中尝试此代码:

Sub HideRows()
    Dim beginRow As Long, endRow As Long, chkCol As Long, chkCommCol As Long, rowCnt As Long

    beginRow = 1
    endRow = cells(Rows.Count, 1).End(xlUp).Row '<--| set 'endRow' to column A last not empty cell row index
    chkCol = 1
    chkCommCol = 17

    Rows.EntireRow.Hidden = False 'unhides all rows. Subsequent code will hide relevant ones 

    If cells(3, chkCommCol).Value = "Yes" Then '<--| if Q3 value is "Yes"
        For rowCnt = beginRow To endRow '<--| loop through the "limit" rows indexes 
            With cells(rowCnt, chkCol) '<--| reference current cell to be cheked
                .EntireRow.Hidden = (.Interior.Color = RGB(253, 233, 217)) '<--| set its corresponding Row 'Hidden' property to True if currently referenced cell has wanted color
            End With
        Next
    End If
End Sub

并将以下代码放在相关的工作表代码窗格中:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$Q" Then HideRows '<--| if "Q3" cell has been changed then run 'HideRows' macro
End Sub