我试图根据第一行中的单元格字体颜色隐藏列。如果第一行中的单元格为黑色字体颜色,我想隐藏列。现在,我不想定义一个范围,因为我的数据每周都有所不同所以我本周可以有10列,下周有20列,我想保持我的代码动态。
看起来我的vba代码经过(按 F8 )没有任何问题,但没有任何反应。我还在下面发布了一个样本和欲望结果。
Sub test()
Dim i As Range
For Each i In Rows(1)
If i.Font.Color = RGB(0, 0, 0) Then
i.EntireColumn.Hidden = True
Else
i.EntireColumn.Hidden = False
End If
Next i
End Sub
答案 0 :(得分:3)
您需要参考范围内的单元格。而且你不需要If语句。尝试:
Sub foo()
Dim c As Range
For Each c In ActiveSheet.UsedRange.Rows(1).Cells
c.EntireColumn.Hidden = c.Font.Color = 0
Next c
End Sub
答案 1 :(得分:2)
您需要使用第一行中的单元格:
Option Explicit
Public Sub HideBlackHeaders()
Dim ws As Worksheet, headerRow As Range, cel As Range
Set ws = Sheet1 'Use the CodeName of the sheet
Set headerRow = ws.UsedRange.Rows(1)
For Each cel In headerRow.Cells
cel.EntireColumn.Hidden = (cel.Font.Color = RGB(0, 0, 0))
Next cel
End Sub
答案 2 :(得分:1)
有点太晚但是试试这个:
Sub test()
Dim i As Long
Dim lColumn As Long
Dim ws As Worksheet: Set ws = ActiveSheet
'Last column
lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To lColumn
If Cells(1, i).Font.Color = RGB(0, 0, 0) Then
Cells(1, i).EntireColumn.Hidden = True
Else
Cells(1, i).EntireColumn.Hidden = False
End If
Next
End Sub