【问题标题】:hide column based on font color in a table vba根据表格vba中的字体颜色隐藏列
【发布时间】:2018-06-29 16:10:08
【问题描述】:

我在 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

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    通过此更改,我们不必费心检测单元格颜色,因为您是根据同一循环中的值进行设置的。测试值,设置颜色,然后一键隐藏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-15
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多