How to hide blank rows in a PivotTable using VBA?

To hide blank rows in a PivotTable using VBA, you can use the following approach. The goal is to loop through the PivotTable items, identify the ones that are blank, and set their `Visible` property to `False`. Here’s a sample VBA macro that demonstrates how to achieve this:

Sub HideBlankRowsInPivotTable()
    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
    Dim fieldName As String
    
    ' Set your worksheet and PivotTable references
    Set ws = ThisWorkbook.Sheets("YourSheetName") ' Change to your sheet name
    Set pt = ws.PivotTables("PivotTable1")        ' Change to your PivotTable name
    fieldName = "YourPivotField"                   ' Change to your field name

    ' Set the PivotField where you expect blanks
    Set pf = pt.PivotFields(fieldName)

    ' Loop through each PivotItem in the field
    For Each pi In pf.PivotItems
        ' Check if the item is blank
        If pi.Name = "(blank)" Then
            pi.Visible = False
        Else
            pi.Visible = True
        End If
    Next pi
End Sub

Explanation:

  • Worksheet and PivotTable References: Replace `”YourSheetName”` with the name of the worksheet containing your PivotTable, and `”PivotTable1″` with the name of your PivotTable.
  • Field Name: Replace `”YourPivotField”` with the name of the pivot field you are checking for blank items.
  • Loop Through PivotItems: The macro iterates over all pivot items within the specified pivot field. It compares each item’s name with `”(blank)”`, which is how Excel labels blank values in PivotTables.
  • Hide Blank Items: When a blank item is found, the `Visible` property is set to `False`, effectively hiding the row associated with that item in the PivotTable.

Make sure to adjust the worksheet name, PivotTable name, and field name to reflect your specific use case. This macro will hide any rows in the PivotTable that are associated with blank values in the specified field.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project