VBA tìm và liệt kê Pivot Table lỗi trong file Excel

 Sub CreateErrorPivotTableList()

    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 = "Location"

    

    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

            On Error Resume Next

            ' Thử Refresh PivotTable

            pt.RefreshTable

            ' Kiểm tra nếu có lỗi xảy ra

            If Err.Number <> 0 Then

                ' 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

                ' Ghi vị trí của PivotTable vào danh sách

                newSheet.Cells(rowIndex, 3).Value = pt.TableRange1.Address

                rowIndex = rowIndex + 1

            End If

            On Error GoTo 0

        Next pt

    Next ws

End Sub

Nhận xét