【问题标题】:Excel: Hide a row if no cells in that row are coloredExcel:如果该行中没有任何单元格着色,则隐藏该行
【发布时间】:2013-03-17 06:35:44
【问题描述】:

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

Sheet2 使用 INDIRECT 公式作为受保护的页面,具有条件格式,如果到期日期即将到来,则将某些单元格突出显示为红色或黄色。

我对 VBA 缺乏经验,一直在寻找符合以下条件的宏:

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

任何帮助将不胜感激。我只找到了根据单列中的条件隐藏行的代码。

【问题讨论】:

标签: vba excel


【解决方案1】:

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

代码:

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

之前

之后

【讨论】:

  • 如果我的措辞有点难以理解,我深表歉意。我需要的是相反的。我需要彩色的行留下来。白色的必须隐藏。
  • 我可能只是误读了 :) 已对原始答案进行了正确更改,现在应该按照您的要求进行。
  • 谢谢!问题:如果 A 列中没有数据输入,则宏不会在该行中运行。此外,如果彩色单元格中没有数据输入 - 宏将隐藏它。这个宏还需要我手动点击才能运行。有没有办法让它在启动时自动运行?有没有办法让它变得动态? IE:由于此工作表链接到另一个工作表,如果另一个工作表上的数据强制单元格更改 Sheet2 上的颜色 - 它可以自动取消隐藏吗?
  • 嗯...也遇到了另一个问题。显然,这个宏只检测手动着色的单元格。如果它们有条件地格式化为突出显示,则它将彩色单元格视为非彩色单元格。如果太麻烦,我理解。感谢您迄今为止的帮助!
  • 上面的代码/示例是作为一个起点,而不是作为一个完整的工作解决方案。我建议你看一下代码并稍微玩一下,通过做一些研究来弄清楚它是如何工作的,然后在这里发布更多关于你尝试过什么以及你卡在哪里的问题。要使其在启动时自动运行,您可以查看将代码放在Workbook_Open 事件中。要在对 Sheet2 进行更改时运行它,您可以查看 Worksheet_Change 事件。
【解决方案2】:
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

【讨论】:

  • OP 想要hide,而不是delete
猜你喜欢
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多