我需要解决完全相同的问题,但希望在更改数据透视表过滤或刷新数据时自动隐藏行,所以我编写了一个从保存数据透视表的工作表上的“Worksheet_PivotTableUpdate”事件调用的函数,虽然如果您愿意,我想您可以按一下按钮。这最初是通过扫描数据透视表中的每一行来完成这项工作的,如果它是可见的并且不需要它则隐藏它(因为该行的第一个单元格是“(空白)”),或者如果它被隐藏并且应该显示它不是,否则只是让它隐藏或可见。
但是,我发现该函数运行得很慢,所以这是我的下一次尝试,它最初取消隐藏数据透视表中的所有行,然后找到第一列中的所有空白单元格,将它们添加到范围对象,然后它隐藏该范围内每个单元格的整行。这个版本的运行速度大约是原来的十倍 :-)
传入数据透视表所在工作表的名称、数据透视表的名称和一个可选字符串,以便在需要隐藏的行中查找;如果调用函数没有提供,则默认为“(空白)”。
如果我违反任何人的变量或函数命名约定,请提前道歉(我只是一个黑客;-))
Sub FixBlankPivotRowsV2(ByVal SheetName As String, ByVal PivotName As String, Optional HideDefn as String = "(blank)")
Dim CurrPivot As PivotTable
Dim CurrRow As Range
Dim BlankRange As Range 'NB This is where we'll build the range of things to hide, which will initially be Nothing, as we never initialise it.
Dim oldStatusBar As Boolean
'Show a nice message in the status bar
oldStatusBar = Application.DisplayStatusBar
Application.DisplayStatusBar = True
Application.StatusBar = "Hiding blank entries in " & SheetName & ", back in a sec..."
Application.ScreenUpdating = False
'Get the pivottable to work with
Set CurrPivot = ActiveWorkbook.Sheets(SheetName).PivotTables(PivotName)
'Unhide all of the pivot rows first
CurrPivot.RowRange.Rows.EntireRow.Hidden = False
'Loop around each row in the pivottable
For Each CurrRow In CurrPivot.RowRange.Rows
If CurrRow.Offset(0, 0).value = HideDefn Then
If BlankRange Is Nothing Then
'This is the first blank row we've found, so just set the range up to be the first cell of that range
Set BlankRange = CurrRow.Offset(0, 0)
Else
'Add the newly found blank row to the range using a Union
Set BlankRange = Union(BlankRange, CurrRow.Offset(0, 0))
End If
End If
Next
'Only hide things if there's anything to hide!
If BlankRange Is Nothing Then
Debug.Print "Nothing to hide!"
Else
BlankRange.EntireRow.Hidden = True
End If
'Set the status bar back the way it was
Application.ScreenUpdating = True
Application.StatusBar = False
Application.DisplayStatusBar = oldStatusBar
End Sub
我寻找一种方法来使用 Go To Special 类型功能之一选择第一列中的所有“空白”单元格,但找不到任何符合要求的内容,所以如果您知道如何,请告诉我做这样的事情,因为它会加快速度。
我希望这可以帮助那里的人!