首页 > 解决方案 > 如何隐藏不包含填充单元格的整列

问题描述

我有一个表格(X x Y),其中随机单元格填充为红色(它的范围可以从列中填充的所有单元格到一些填充的单元格,再到列中没有填充的单元格)。我想隐藏没有填充单元格的列。下面的代码查找填充为红色的单元格并隐藏整个列,无论是否有任何未填充的单元格。我想隐藏没有填充单元格的列在。

 Dim cell As Range
  For Each cell In Selection
  If cell.Interior.Color = vbRed Then 'finds the filled in cells
  Columns(cell.Column).EntireColumn.Hidden = True 'hides the column with filled in cells
  End If
  Next

先感谢您。

标签: excelvba

解决方案


我想也许你需要确定一个变量来记录需要隐藏或不隐藏的状态。在这里,我命名为“标志”来记录是否需要隐藏列。

Sub Hidden_Column()
Dim Flag As Boolean
Dim iRow As Integer
Dim iClm As Integer
Dim ColorNum

With Sheet1
    For iClm = 1 To .Cells(1, 256).End(xlToLeft).Column
        Flag = True
        For iRow = 1 To .Cells(65536, 1).End(xlUp).Row
            ColorNum = .Cells(iRow, iClm).Interior.ColorIndex
            If ColorNum <> -4142 Then       'no color
                Flag = False
                Exit For
            End If
        Next iRow
        If Flag = True Then
            Columns(Cells(iRow, iClm).Column).EntireColumn.Hidden = True
        End If
    Next iClm
End With
End Sub

推荐阅读