隐藏2个范围的列

时间:2018-03-02 13:15:52

标签: excel vba excel-vba

我必须在范围为空时隐藏列,并且我在不同的工作表中有2个范围来控制何时隐藏或取消隐藏这些列。 我正在尝试使用带有2个变量的FOR循环,但我没有工作,这是我的代码:

Sub HiddenColumns()

    Dim HiddenColumn1 As Range
    Dim HiddenColumn2 As Range

    Dim c As Range
    Dim d As Range


    Set HiddenColumn1 = Range("rngColumnHidden")
    Set HiddenColumn2 = Range("rngColumnHidden2")

    For Each c In HiddenColumn1
        For Each d In HiddenColumn2

            If c.Value = "" Then
                c.EntireColumn.Hidden = True
                If d.Value = "" Then
                d.EntireColumn.Hidden = True
                End If
            End If
        Next d
    Next c

End Sub

使用一个范围它可以正常工作,但是当我尝试隐藏另一个范围时,我遇到了问题,这是一个范围的代码:

Sub HiddenColumns()

    Dim HiddenColumn1 As Range
    Dim c As Range

    Set HiddenColumn1 = Range("rngColumnHidden")
    For Each c In HiddenColumn1

            If c.Value = "" Then
                c.EntireColumn.Hidden = True
            End If
    Next c

End Sub

1 个答案:

答案 0 :(得分:1)

在OP的评论后编辑

不要嵌套循环

Sub HiddenColumns()
    Dim c As Range

    For Each c In Range("rngColumnHidden").Rows(1).Cells
        c.EntireColumn.Hidden = (c.Value = "")
    Next c

    For Each c In Range("rngColumnHidden2").Rows(1).Cells
        c.EntireColumn.Hidden = (c.Value = "")
    Next c
End Sub

为了避免代码重复,您可以使用辅助子代码和代码

Sub HiddenColumns()
    HideColumns Range("rngColumnHidden")
    HideColumns Range("rngColumnHidden2")
End Sub

Sub HideColumns(columnsRng As Range)
    Dim c As Range
    For Each c In columnsRng.Rows(1).Cells
        c.EntireColumn.Hidden = (c.Value = "")
    Next c
End Sub