Excel VBA隐藏基于单元格颜色的行,如果命令显示“是”

我试图根据两个标准来隐藏行:

准则1:如果单元格Q3的值为“是”,则隐藏符合条件2的单元格

标准2:如果列A中的单元格是RGB(253,233,217)的颜色,则隐藏整行。

从本质上讲,我有一个跟踪每天电子邮件数的日子列表,我想隐藏任何周末,所以他们不显示在显示趋势图。 我正在把自己的上司弄糊涂了,所以他们只需点击单元格Q3中的“是”或“否”来隐藏周末行。 周末是浅橙色(上面列出的RGB代码)。 如果单元格Q3表示“否”,则所有行都将取消隐藏/保持不被隐藏也是重要的。 我现在的代码是:

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 

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

你可以在任何模块代码窗格中尝试下面的代码:

 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$3" Then HideRows '<--| if "Q3" cell has been changed then run 'HideRows' macro End Sub 

首先,你在整个代码中缺less了一些End If语句,我已经用一些缩进来编辑你的问题,以帮助显示它们的位置,尝试在未来缩进以确保closuresLoopsIf语句。

关于你的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 
Interesting Posts