VBA; 无效的过程或参数错误

一点背景; 我必须在上周的星期一为我的工作运行周报,但是我需要整理材料,我做了一个数据透视表,我必须为多个工作表执行此操作。 但是我决定创build一个macros来完成这个冗余任务。 现在创build它似乎得到这个错误消息“无效的过程或参数”。 我无法在新的工作表中打开它,这是我的代码>>

Sub weekmaster() ' ' weekmaster Macro ' Macro for the week ' ' Keyboard Shortcut: Ctrl+t ' Cells.Select Sheets.Add ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ "weekmaster!R1C1:R1048576C62", Version:=xlPivotTableVersion12). _ CreatePivotTable TableDestination:="Sheet9!R3C1", TableName:="PivotTable1" _ , DefaultVersion:=xlPivotTableVersion12 Sheets("Sheet9").Select Cells(3, 1).Select With ActiveSheet.PivotTables("PivotTable1").PivotFields("Order ID") .Orientation = xlRowField .Position = 1 End With 

如果您不止一次运行macros,或者Sheet9已经存在(因为macros试图在同一张纸上创build同名的同一个数据透视表),将会出错。 如果我假定每次访问数据表并运行macros时都会在工作表中生成一个数据透视表,则可以使用以下代码更新代码:

 Dim myRange as Range dim myNewSheet as Worksheet ' Stores all continuous data on the sheet in the myRange variable Set myRange = Range("A1").CurrentRegion ' Adds a new sheet and stores it in the myNewSheet variable Set myNewSheet = Sheets.Add ' Use the variables to create the new pivot table ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ myRange, Version:=xlPivotTableVersion12).CreatePivotTable _ TableDestination:=myNewSheet.Cells(3, 1), DefaultVersion _ :=xlPivotTableVersion12 ' Select your Order ID field With myNewSheet.PivotTables(1).PivotFields("Order ID") .Orientation = xlRowField .Position = 1 End With 

看来你缺less一个参数。 CreatePivotTable接受以下参数:

expression.CreatePivotTable(TableDestination,TableName,ReadData,DefaultVersion)

  1. TableDestination必需variables数据透视表的数据透视表的左上angular的单元格的目标范围(工作表上的结果数据透视表将放置在其中的范围)。 目标范围必须位于包含由expression指定的PivotCache对象的工作簿中的工作表上。
  2. TableName可选Variant新的数据透视表报告的名称。
  3. ReadData可选Variant True创build包含外部数据库中所有logging的数据透视表caching; 这个caching可能非常大。 假使在数据被实际读取之前将一些字段设置为基于服务器的页面字段。
  4. DefaultVersion可选Variant数据透视表的默认版本。

随后,您可能需要在TableName和DefaultVersion之间添加“true”。

干杯,LC