录制的macros给运行时错误5

我是VBA新手。 我logging了一个macros,并想编辑它。 logging完之后,我想运行一次。 但是当我这样做,它返回运行时错误5。

macros应该从一个表单中取出,并将其添加到另一个表单中的数据透视表中。

所以这是错误所在的代码。

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ "sourcetable!R1C1:R1048576C21", Version:=xlPivotTableVersion14). _ CreatePivotTable TableDestination:="Tabelle2!R3C1", TableName:= _ "PivotTable1", DefaultVersion:=xlPivotTableVersion14 

谢谢你的帮助

不,这不是一个新的工作表只为这个枢纽@SiddharthRout – 初学者4分钟前

最简单的方法是

 With ActiveWorkbook .Sheets("Tabelle2").Cells.Clear .PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ "sourcetable!R1C1:R1048576C21", Version:=xlPivotTableVersion14). _ CreatePivotTable TableDestination:="Tabelle2!R3C1", TableName:= _ "PivotTable1", DefaultVersion:=xlPivotTableVersion14 End With 

另外我注意到,你有源数据定义,直到1048576行。为什么? 更完美的方法是find最后一行然后构build你的范围。 例如

 Sub Sample() Dim lRow As Long With ActiveWorkbook '~~> Find last row in sheet sourcetable With .Sheets("sourcetable") If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lRow = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else lRow = 1 End If End With .Sheets("Tabelle2").Cells.Clear .PivotCaches.Create(SourceType:=xlDatabase, _ SourceData:="sourcetable!R1C1:R" & _ lRow & _ "C21", _ Version:=xlPivotTableVersion14).CreatePivotTable _ TableDestination:="Tabelle2!R3C1", _ TableName:="PivotTable1", _ DefaultVersion:=xlPivotTableVersion14 End With End Sub 

首先:是否存在源表和Tabelle2工作表?

然后,尝试删除所有可选的无意义参数:

 ActiveWorkbook.PivotCaches.Create(xlDatabase, "sourcetable!R1C1:R1048576C21") _ .CreatePivotTable ActiveWorkbook.Worksheets("Tabelle2").Range("R3C1")