创建一个可以打开多个文件并向每个文件添加数据透视表的宏。所有文件的格式都与包含“数据透视表”所需数据的工作表“详细信息”相同。但是,每个文件的行数都不同,因此我尝试使用动态范围来捕获每个文件上的所有数据。
上面的代码打开文件并根据需要对文件进行格式化,以与数据透视表一起使用。
'Set Dynamic Range
Dim startCell As String
Dim lastRow As Long
Dim lastCol As Long
Dim WS As String
WS = "Details"
Worksheets(WS).Activate
'Find Last row and column
lastRow = Cells(Rows.Count, Cells(1, 7).Column).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(1, 7), Cells(lastRow, lastCol)).Select
Range(Range("G1"), Range("G1").End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Name = "DynamicRange"
Sheets.Add After:=ActiveSheet
' Create Pivot Table
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"DynamicRange", Version:=6).CreatePivotTable TableDestination:= _
"Sheet1!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet1").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1")
.ColumnGrand = True
.HasAutoFormat = True
当我进入“创建数据透视表”部分时,第一行给出了运行时错误代码1004。
答案 0 :(得分:1)
您应尽可能避免使用Select
和Activate
。我在下面修改了您的代码。您可能需要重新检查范围值。创建之前,您需要定义PivotCache
和PivotTable
。
Dim startCell As String
Dim lastRow As Long
Dim lastCol As Long
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim PvtCache As PivotCache
Dim PvtTab As PivotTable
Set ws = Sheets("Details")
'Find Last row and column
lastRow = ws.Cells(ws.Rows.Count, 7).End(xlUp).Row
lastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
ws.Range(ws.Cells(1, 7), ws.Cells(lastRow, lastCol)).Name = "DynamicRange"
Set ws2 = Sheets.Add(After:=ws)
ws2.Name = "PvtTable"
' Create Pivot Table
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Range("DynamicRange"))
Set PvtTab = PvtCache.CreatePivotTable(ws2.Cells(1, 1), "MyTable")