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

时间:2017-03-06 13:36:22

标签: excel vba excel-vba row show-hide

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

标准1:如果单元格Q3具有值"是"隐藏符合标准2的单元格

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

基本上,我有一个跟踪每天电子邮件数量的日期列表,我希望隐藏任何周末,以便它们不会显示在显示趋势的图表上。我把我的上级搞砸了,所以他们所要做的就是点击"是"或"不"从单元格Q3中的下拉来隐藏周末行。周末是浅橙色(上面列出的rgb代码)。同样重要的是,如果单元格Q3表示" no"然后所有行都取消隐藏/保持不被隐藏。我现在的代码是:

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

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

2 个答案:

答案 0 :(得分:1)

首先,你在整个代码中遗漏了一些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

答案 1 :(得分:0)

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

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