VBA 选择包含文本的列和用于隐藏所有其他列的切换按钮

问题描述

提前致谢。我需要创建一个切换按钮来根据列标题 Row(1:1) 的文本是否包含 'x' 来隐藏/取消隐藏所有列

如果这些列标题的格式不同,这将有助于我的目的。

我从 Macro1 开始(用于基于文本包含的条件格式)并尝试使用此代码来帮助编写其余部分,但尚未成功。以下供参考。

主要目标是创建函数显示标题为黄色的任何列并隐藏所有其他列。

Function IsYellow(Rge As Range) As Boolean

If Rng.Cells.Interior.Color = 10284031 Then IsYellow = True

End Function

Sub Hide_x()

'Description: This macro will loop through a row and
'hide the column if the cell in row 1 of the column
'has the value of X.



Dim c As Range
    For Each c In Rows("1:1")
        If IsYellow(c) = False Then
            'The following line changes the hidden property to
            'the opposite of it's current setting for the column.
            c.EntireColumn.Hidden = True
            '= Not c.EntireColumn.Hidden.
        End If
    Next c


End Sub


PLEASE HELP! 



FYI


///////
Sub Macro1()
'
' Macro1 Macro
'

'
    ActiveCell.Offset(-4,0).Rows("1:1").EntireRow.Select
    Selection.FormatConditions.Add Type:=xlTextString,String:="TEXT",_
        TextOperator:=xlContains
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Font
        .Color = -16754788
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 10284031
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False
End Sub



'RGB(255,235,156)

解决方法

试试这个。它将切换 Row1 中的值包含“x”的所有列的可见性

Sub TogglexHidden()

    'Description: This macro will loop through a row and
    'hide/unhide the column if the cell in row 1 of the column
    'contains X.
    Dim c As Range,rngHeaders As Range,hiding As Boolean,foundFirst As Boolean
    
    With ActiveSheet.Rows(1) 'or specify some other sheet
        'set the range to oop over (not the whole row)
        Set rngHeaders = .Range(.Cells(1),.Cells(.Columns.Count).End(xlToLeft))
        rngHeaders.Select
    End With
    
    For Each c In rngHeaders
        If UCase(c.Value) Like "*X*" Then  'checking directly for "x"
        'If c.DisplayFormat.Interior.Color = 10284031 Then 'if you prefer to use color to check
            If Not foundFirst Then
                'are we hiding,or unhiding ? (based on whether the first
                '  one we found was already hidden or not)
                hiding = Not c.EntireColumn.Hidden
                foundFirst = True 'have now checked the first column with "x"
            End If
            c.EntireColumn.Hidden = hiding 'set the visibility
        End If
    Next c

End Sub