Excel:如果该行中的单元格未着色,则隐藏一行

时间:2013-03-27 08:26:57

标签: excel vba excel-vba

对于A列和B列中某些列出的名称,我有一个工作簿设置为Sheet1可编辑的多个列(列C到T)中的到期日期。第1行和第1行是标题,因此数据输入从第3行开始。

Sheet2与使用INDIRECT公式作为受保护页面完全相同,带有条件格式,如果到期日期即将突出显示某些单元格为红色或黄色。

我对VBA缺乏经验,并且一直在寻找符合以下标准的宏:

仅在Sheet2上,如果该行不包含任何红色或黄色的单元格,则隐藏这些非彩色行。

非常感谢任何帮助。我只根据单列中的条件找到了隐藏行的代码。

2 个答案:

答案 0 :(得分:4)

这是一个让你入门的小脚本。它将遍历每行的每一列并检查每个单元格的颜色。如果找到任何颜色,将跳过该行。如果找不到任何颜色的单元格,则该行将被隐藏。换句话说,所有全白行都将被隐藏

<强> CODE:

Public Sub HideUncoloredRows()
    Dim startColumn As Integer
    Dim startRow As Integer

    Dim totalRows As Integer
    Dim totalColumns As Integer

    Dim currentColumn As Integer
    Dim currentRow As Integer

    Dim shouldHideRow As Integer

    startColumn = 1     'column A
    startRow = 1        'row 1
    totalRows = Sheet2.Cells(Rows.Count, startColumn).End(xlUp).Row

    For currentRow = totalRows To startRow Step -1
        shouldHideRow = True
        totalColumns = Sheet2.Cells(currentRow, Columns.Count).End(xlToLeft).Column
        'for each column in the current row, check the cell color
        For currentColumn = startColumn To totalColumns
            'if any colored cell is found, don't hide the row and move on to next row
            If Not Sheet2.Cells(currentRow, currentColumn).Interior.ColorIndex = -4142 Then
                shouldHideRow = False
                Exit For
            End If
        Next

        If shouldHideRow Then
            'drop into here if all cells in a row were white
            Sheet2.Cells(currentRow, currentColumn).EntireRow.Hidden = True
        End If
    Next
End Sub

<强> BEFORE

enter image description here

<强> AFTER

enter image description here

答案 1 :(得分:0)

row = 1    
do
  flag = false
  col = 1
  do
    .cells(row,col).select
    if selection.interior.colorindex <> vbWhite then flag = true
  loop until (col = lastcol) or (flag = true)
  if flag then 
    rows(row).delete
    row = row - 1
  end if
  row = row + 1
loop until row = lastrow