Excel VBA函数隐藏/取消隐藏行

时间:2018-08-31 19:28:57

标签: excel excel-vba excel-formula

我是VBA /宏的新手。我需要一些帮助来确定如何根据给定场景隐藏/取消隐藏行。这是我的桌子:

请参阅表格:enter image description here

我想做的是:

1)创建带有三个参数的函数(或子):

  • FlagRange:flagRange或C1:C9
  • hideAction:对/错
  • 标志:这是标志值之一

示例:Hide_Unhide(flagRange,True,“ P”)

2)此函数将根据传递给参数的Flag隐藏所有行。

任何建议和示例都值得赞赏。

3 个答案:

答案 0 :(得分:1)

这里有两个选择。第二个子元素将更快,因为它将立即隐藏所有行,并且可能隐藏许多行。要隐藏的行数越大,使用Union方法所节省的时间就越多

Option Explicit

Sub HideMe(FlagRange As Range, Flag As String)

FlagRange.EntireRow.Hidden = False
Dim FlagCell As Range

Application.ScreenUpdating = False
    For Each FlagCell In FlagRange
        FlagCell.EntireRow.Hidden = FlagCell = Flag 'Rows get hidden here
    Next FlagCell
Application.ScreenUpdating = True

End Sub

Option Explicit

Sub HideMeUnion(FlagRange As Range, Flag As String)

FlagRange.EntireRow.Hidden = False
Dim FlagCell As Range, HideMe As Range

For Each FlagCell In FlagRange
    If FlagCell = Flag Then
        If HideMe Is Nothing Then
            Set HideMe = FlagCell
        Else
            Set HideMe = Union(HideMe, FlagCell)
        End If
    End If
Next FlagCell

'rows gettin hidden here all at once
If Not HideMe Is Nothing Then HideMe.EntireRow.Hidden = True

End Sub

答案 1 :(得分:0)

尝试一下:

Private sub Hide_Unhide(FlagRange as Range, Hide as Boolean, FlagValue as String)
Dim c as Variant
    For Each c in FlagRange
           c.EntireRow.Hidden = False
    Next c
    For Each c in FlagRange
        If c.Value2 = FlagValue Then
           c.EntireRow.Hidden = Hide
        End IF
    Next c
End Sub

答案 2 :(得分:-1)

您可以使用以下解决方案隐藏/取消隐藏行:

Function Hide_Unhide(flagRange As Range, hideAction As Boolean, Flag As String)
        For Each Row In flagRange.Rows
            If Row.Cells(3) = Flag Then
                Row.EntireRow.Hidden = hideAction
            End If
        Next Row
End Function