【发布时间】:2019-09-02 18:19:43
【问题描述】:
我录制了一个宏来从一个数据源获取数据透视表,并将代码分配给一个按钮。
代码在我第一次执行宏时有效
当我第二次重新运行宏时,它给出了一些运行时错误。我知道表目标范围中已经存在表的原因。如何使我的宏使按钮仅工作一次或仅在源数据表中的数据发生更改时工作?
示例代码
Sub pivotexample()
Dim pt As PivotTable
Sheets("pivot_view").Select
For Each Pt In Sheets("pivot_view").PivotTables
Sheets("pivot_view").Range(PT.TableRange2.Address).Delete Shift:=xlUp
Next PT
Sheets("result").Select
Cells.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"result!R1C1:R1048576C26", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="pivot_view!R8C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion14
Sheets("pivot_view").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("week_name")
.Orientation = xlPageField
.Position = 1
'code for all the pivot table fields.
End With
Set pt = Worksheets("pivot_view").PivotTables("PivotTable1")
Range("A8").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range("A8:I8").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.UsedRange.Copy
Range("A9").Offset(pt.TableRange1.Rows.Count, 0).Select
ActiveSheet.Paste
With ActiveSheet.PivotTables("PivotTable2").PivotFields("task_queue_name") 'getting error in this line, when i run the code for once, it is working fine, the name of the pivotTable2 would be pivotTable2 only, but when i remove the old pivot tables using the loop you have suggested and run that for the second time, the name of the second pivot table is getting changed.
.Orientation = xlRowField
.Position = 2
End With
end sub
【问题讨论】:
-
请贴出代码
-
嗨@andreas Hofmann,谢谢,我刚刚发布了示例代码,您可以检查一次吗?