PivotCaches.Add Errors out

一个人想着一个人 提交于 2019-11-29 18:06:08

The reason why you are getting that error is because your are supposed to use .Create instead of .Add

Set MyPivotCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, MyPivotRangeName)

EDIT

Further to my comments under your question, you code could be optimized (UNTESTED) like this

Sub Sample()
    Dim wb As Workbook
    Dim ws As Worksheet, newWs As Worksheet
    Dim sFile As String, MyPivotRangeName As String
    Dim MyPivotRange As Range
    Dim pt As PivotTable
    Dim MyPivotCache As PivotCache

    sFile = "C:\Users\srujan\Desktop\TIME REPORT\fresh\25_Report Time Booking_25.xls"

    Set wb = Workbooks.Open(sFile)
    Set ws = wb.Sheets("25_Report Time Booking_25")
    Set newWs = wb.Worksheets.Add

    With ws
        Set MyPivotRange = .Range("A1:G78")

        MyPivotRangeName = "'" & ws.Name & "'!" & MyPivotRange.Address(ReferenceStyle = xlR1C1)

        Set MyPivotCache = wb.PivotCaches.Create( _
                          SourceType = xlDatabase, _
                          SourceData = MyPivotRangeName)

        Set pt = MyPivotCache.CreatePivotTable( _
        tabledestination:=(newWs.Name & "!R3C1"), _
        tablename:="PivotTable1")

        '
        '~~> Rest of the code
        '
    End With
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!