VBA liệt kê danh sách Table/PivotTable có trong file Excel

Sub ListPivotTables()

    Dim ws As Worksheet

    Dim newSheet As Worksheet

    Dim pt As PivotTable

    Dim rowIndex As Long

    

    ' Tạo một sheet mới để lưu trữ danh sách

    Set newSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))

    

    ' Đặt tiêu đề cho danh sách

    newSheet.Range("A1").Value = "Worksheet"

    newSheet.Range("B1").Value = "PivotTable Name"

    newSheet.Range("C1").Value = "Source Range"

    newSheet.Range("D1").Value = "Table address "

    

    rowIndex = 2 ' Vị trí hàng bắt đầu ghi dữ liệu

    

    ' Duyệt qua tất cả các worksheet trong tệp Excel

    For Each ws In ThisWorkbook.Worksheets

        ' Duyệt qua tất cả các PivotTable trong worksheet

        For Each pt In ws.PivotTables

            ' Ghi tên worksheet vào danh sách

            newSheet.Cells(rowIndex, 1).Value = ws.Name

            ' Ghi tên PivotTable vào danh sách

            newSheet.Cells(rowIndex, 2).Value = pt.Name

            ' Chuyển đổi địa chỉ nguồn dữ liệu từ R1C1 sang A1

            Dim sourceAddress As String

            sourceAddress = pt.SourceData

            newSheet.Cells(rowIndex, 3).Value = Application.ConvertFormula(sourceAddress, xlR1C1, xlA1)

            ' Lấy địa chỉ của PivotTable (dưới dạng A1:B10)

            newSheet.Cells(rowIndex, 4).Value = pt.TableRange2.Address

            rowIndex = rowIndex + 1

        Next pt

    Next ws

End Sub

Nhận xét