将一个宏应用于另一个工作表/工作簿,无论工作簿的名称或工作簿名称如何
问题描述:
我有一个返回错误的宏的问题,并且我想知道您是否可以在此问题上提供一些信息。将一个宏应用于另一个工作表/工作簿,无论工作簿的名称或工作簿名称如何
我有宏如下所示:
Sub pivot1_macro()
'
' pivot1_macro Macro
'
' Keyboard Shortcut: Ctrl+Shift+M
'
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"7-14 week!R1C2:R199C35", Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Sheet5!R3C1", TableName:="PivotTable3", DefaultVersion _
:=xlPivotTableVersion15
Sheets("Sheet5").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable3").PivotFields("PartMOD")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable3").PivotFields("EnteredShift")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Defect")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables(_
"PivotTable3").PivotFields("Defect Quantity"), "Sum of Defect Quantity", xlSum
Columns("D:D").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
Columns("B:B").EntireColumn.AutoFit
Columns("C:C").EntireColumn.AutoFit
Columns("D:D").EntireColumn.AutoFit
Range("B3").Select
Range("B3").Select
End Sub
我想这个宏适用于任何活动工作,但我不能肯定 如何使设置'SourceData'
当前活动工作表。
答
您可以使用“&”来连接字符串,这样就不会
你SourceData := ActiveSheet.Name & "!R1C2:R199C35"
工作来获取当前工作表的名称?
删除表名#7-14周!'? –
快速注意,它是[最好避免'.Activate' /'.Select'](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) ,因为它会导致意想不到的结果。 – BruceWayne