Refresh Data and Pivot Tables in Excel Using VBA

The following Excel VBA macro can be used to refresh external data lists and the associated pivot tables within the workbook programmatically. This procedure is useful to provide users with an ability to generate Excel reports as needed with the latest data.

Sub refresh_data()
    Dim pt As PivotTable
    Dim ws As Worksheet
    Dim pc As PivotCache
    Dim lo As ListObject
    
    'Change setting in each Pivot Table to remove stale or missing items
    For Each ws In ActiveWorkbook.Worksheets
      For Each pt In ws.PivotTables
        pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
      Next pt
    Next ws

    'Refresh each Pivot Cache to clear stale entries
    For Each pc In ActiveWorkbook.PivotCaches
      On Error Resume Next
      pc.Refresh
    Next pc

    'Refresh each List Object to retrieve latest external data
    For Each ws In ActiveWorkbook.Worksheets
        For Each lo In ws.ListObjects
            lo.Refresh
        Next
    Next

    'Refresh all Pivot Tables
    For Each ws In ActiveWorkbook.Worksheets
      For Each pt In ws.PivotTables
        pt.RefreshTable
      Next pt
    Next ws

End Sub

2 thoughts on “Refresh Data and Pivot Tables in Excel Using VBA”

Leave a Comment