首页 > 解决方案 > 如果计数为 0,函数中带有参数,则隐藏基于多列值的行

问题描述

我需要一个函数,我将过滤的数据范围作为HideRangeIfEmpty函数中的参数传递。但是,我的代码隐藏了循环中所有为空的行。

仅当过滤可见数据计数(例如 G5、T5、AG5 为零)为零时,预期的输出应该是必须隐藏的行。

Case "UsGe"
Application.ScreenUpdating = False
ActiveSheet.Range("F:BC").EntireColumn.Hidden = True
ActiveSheet.Range("G:G,T:T,AG:AG").EntireColumn.Hidden = False
Range("a1").Select
Call HideRangeIfEmpty("G6:AG200")

Private Sub HideRangeIfEmpty(R1)
For Each xRg In Range(R1)
    If xRg.Value = "" Then
      xRg.EntireRow.Hidden = True
     Else
      xRg.EntireRow.Hidden = False
    End If
   Next xRg
 End Sub

标签: excelvba

解决方案


您可以通过将相关列作为多范围来处理相关列:

Private Sub UsGe()
    ' ...
    Call HideRangeIfEmpty(ActiveSheet.Range("G6:G200, T6:T200, AG6:AG200"))
End Sub

如果任何列的值为 <> "",则将显示该行,否则不显示:

Private Sub HideRangeIfEmpty(ByRef r As Range)
    Dim CurrentRow As Long, CurrentArea As Long, CurrentColumn As Long
    Dim ToBeShown As Boolean

    ' Check each row (defined by the first area)
    For CurrentRow = 1 To r.Areas(1).Rows.Count

        ToBeShown = False   ' default: not hidden

        ' check each area (one or more columns)
        For CurrentArea = 1 To r.Areas.Count

            ' check cell in each column
            For CurrentColumn = 1 To r.Areas(CurrentArea).Columns.Count

                ' If any has a value, then set the marker
                If r.Areas(CurrentArea).Cells(CurrentRow, CurrentColumn) <> "" Then _
                    ToBeShown = True
            Next CurrentColumn
        Next CurrentArea

        ' show complete row, if marker is set
        r.Areas(1).Cells(CurrentRow, 1).EntireRow.Hidden = Not ToBeShown
    Next CurrentRow
End Sub

现在它也适用于像“G6:I200”这样的范围,我的代码将检查列 G、H 和 I。


推荐阅读