隐藏表格中基于字体颜色的列VBA

时间:2018-06-29 16:10:09

标签: vba excel-vba excel

我在sheet1中有一些数据作为表(名为Table1),并且我正在根据名称更改某些标题的字体颜色,并且我只想在标题颜色为黑色时隐藏标题,因此请保持橙色和白色-隐藏。当我打开原始工作表时,列标题的字体颜色为白色。

现在,当我运行代码时,没有任何错误,但是我只看到带有橙色字体颜色标题的列,这是不正确的。由于某种原因,当我将数据转换为范围时,它可以工作,但是我不想使用unlist并为数据重新创建表。

Sub Data_Formatting()
   Dim i, j, k As Long      
Range(Range("A1"), Range("A1").End(xlToRight)).Interior.Color = RGB(79, 129, 189)
 Last = Cells(1, Columns.Count).End(xlToLeft).Column
    For i = Last To 1 Step -1
        If (Cells(1, i).Value) = "System" Then
         Cells(1, i).Font.Color = RGB(0, 0, 0)
        End If
    Next i   
    For j = Last To 1 Step -1
        If (Cells(1, j).Value) = "AOB" Then
            Cells(1, j).Font.Color = RGB(255, 153, 0)
        End If
    Next j    
Range("A:D").Columns.AutoFit
    Dim l 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 l = 1 To lColumn
        If Cells(1, l).Font.Color = RGB(0, 0, 0) Then
            Cells(1, l).EntireColumn.Hidden = True
        Else
            Cells(1, l).EntireColumn.Hidden = False
        End If
    Next
End Sub

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您只需要在此处循环一次,然后在该循​​环中执行所有逻辑即可。现在,您的操作方式是在同一组列上循环3次,只是执行的操作略有不同。

Sub Data_Formatting()
    Dim i as Long    

    'set the background to blue
    Range(Range("A1"), Range("A1").End(xlToRight)).Interior.Color = RGB(79, 129, 189)

    'Find last cell
    Last = Cells(1, Columns.Count).End(xlToLeft).Column

    'autofit before hiding
    Range("A:D").Columns.AutoFit

    'loop once
    For i = Last To 1 Step -1       
        If (Cells(1, i).Value) = "System" Then
            Cells(1, i).Font.Color = RGB(0, 0, 0) 'black
            Columns(i).Hidden = True
        ElseIf Cells(1, j).Value = "AOB" Then
            Cells(1, j).Font.Color = RGB(255, 153, 0) 'orange
            Columns(i).Hidden = False
        End If
    Next i  
End Sub

通过此更改,我们不必费心检测单元格颜色,因为您是基于同一循环中的值进行设置的。测试该值,设置颜色并将其全部隐藏起来。