将Excel工作表名称传递给macrosVB

我认为这应该是一个简单的,考虑到我有很less的VB知识:)我已经logging了一个macros,为当前表格上的范围创build数据透视表。 当然,这给了我的是为特定工作表创build数据透视表的代码。 我正在尝试调整代码以获取活动工作表的名称,以便可以在不同工作表中使用此macros。 我试图search并find如何检索名称,然后将该名称提供给将创build数据透视表的过程的代码。

我在代码的ActiveWorkbook.PivotCaches.Create部分打了一个障碍。 我得到“运行时错误”1004“:应用程序定义的或对象定义的错误”消息。

任何帮助将不胜感激!

Sub Macro1() Dim sht As String sht = ActiveSheet.Name Columns("A:K").Select ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ Worksheets(sht).Range("!R1C1:R1048576C11"), Version:=6).CreatePivotTable TableDestination:= _ Worksheets(sht).Range("!R1C14"), TableName:="PivotTable3", DefaultVersion:=6 ActiveSheet.Select Cells(1, 14).Select With ActiveSheet.PivotTables("PivotTable3").PivotFields("Department") .Orientation = xlRowField .Position = 1 End With With ActiveSheet.PivotTables("PivotTable3").PivotFields( _ "Originating Master Name") .Orientation = xlRowField .Position = 2 End With With ActiveSheet.PivotTables("PivotTable3").PivotFields("Net") .Orientation = xlRowField .Position = 3 End With With ActiveSheet.PivotTables("PivotTable3").PivotFields("Month") .Orientation = xlRowField .Position = 4 End With ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _ "PivotTable3").PivotFields("Net"), "Count of Net", xlCount With ActiveSheet.PivotTables("PivotTable3").PivotFields("Month") .Orientation = xlColumnField .Position = 1 End With With ActiveSheet.PivotTables("PivotTable3").PivotFields("Count of Net") .Caption = "Sum of Net" .Function = xlSum End With End Sub 

改变这一点

 Worksheets(sht).Range("!R1C1:R1048576C11") 

对此

 ActiveWorkbook.Sheets(sht).Range("A1:K1048576") 

和这个

  Worksheets(sht).Range("!R1C14") 

对此

  ActiveWorkbook.Sheets(sht).Range("N1")