简体   繁体   English

不论工作表或工作簿名称如何,都将一个宏应用于另一工作表/工作簿

[英]Apply one macro to another sheet/workbook regardless of sheet or workbook name

I have an issue with macros returning errors, and I was wondering if you guys could shed some light on this issue. 我有一个宏返回错误的问题,我想知道你们是否可以阐明这个问题。

The macro I have looks like the following: 我拥有的宏如下所示:

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

I'd like to apply this macro to any active worksheet, but I'm not quite sure how to make set 'SourceData' to current active worksheet. 我想将此宏应用于任何活动的工作表,但我不确定如何将'SourceData'设置为当前的活动工作表。

You can use '&' to concatenate strings, so wouldn't 您可以使用“&”连接字符串,因此不会

SourceData := ActiveSheet.Name & "!R1C2:R199C35"

work for you to get the current sheet's name? 为您工作以获取当前工作表的名称?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM