VBA: Error on creating a pivot table

耗尽温柔 提交于 2020-01-06 20:11:37

问题


I am creating a VBA macro. Among other things, it makes a pivot table:

    ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Working").UsedRange).CreatePivotTable TableDestination:="", TableName:="HDPivotTable", DefaultVersion:=xlPivotTableVersion10

This works, but when I delete all data from the Excel spreadsheet and replace it with new data of the same structure, I get an error on the above line:

Run-time error '13': Type mismatch

Could you please help me on this?

Thanks.

EDITED:

After applying Scott's suggestion, I get another error:

With Worksheets("Working")
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row
    lColumn = .Range("A" & .Columns.Count).End(xlToLeft).Column
    ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=.Range(.Cells(1, 1), .Cells(lRow, lColumn))).CreatePivotTable TableDestination:="", TableName:="HDPivotTable", DefaultVersion:=xlPivotTableVersion10
End With

ActiveSheet.Name = "HD Pivot"
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1)
ActiveSheet.PivotTables("HDPivotTable").AddFields RowFields:="Location Code"

The error is: Run-time error '1004': AddFields method of PivotTable class failed


回答1:


Most likely what is causing the error is the use of UsedRange. While a nifty tool, it also has its drawbacks, especially since you are now replacing data.

For example, if the new data has less columns then the old data, or even less rows, the UsedRange will most likely reflect the old range with data. Furthermore, depending upon what you have been doing with your worksheet there may be cells that contain formatting or other characters that you cannot see with the naked-eye, that will affect the UsedRange.

If you make the following adjustments in your code, it should work every time.

Dim ws as Worksheet
Set ws = Worksheets("Working")

Dim lRow as Long, lColumn as Long

'assumes data table of contiguous rows/columns starting in A1
With ws
    lRow = .Range("A" & .Rows.Count).End(xlup).Row
    lColumn = .Cells(1, .Columns.Count).End(xltoLeft).Column
End With

ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=ws.Range(ws.Cells(1,1),ws.Cells(lRow,lColumn)) ...


来源:https://stackoverflow.com/questions/35461122/vba-error-on-creating-a-pivot-table

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