简体   繁体   English

VBA 从数据透视表复制和粘贴总计

[英]VBA to copy and paste Grand Total from Pivot Table

I am hoping to create a macro to copy the value of a grand total from a pivot table on another workbook and paste it to ThisWorkbook.我希望创建一个宏来从另一个工作簿的数据透视表中复制总计的值并将其粘贴到 ThisWorkbook。 Here is what I have so far:这是我到目前为止所拥有的:

Notes:笔记:

  • I do not want to just copy the bottom right cell value of the Pivot Table as that has been a solution to other questions asked before.我不想只复制数据透视表右下角的单元格值,因为这已经解决了之前提出的其他问题。 I will eventually need to copy from multiple Grand Totals that are not in the bottom right corner.我最终需要从不在右下角的多个总计中复制。
  • Currently getting Run-time error 424. Object required当前出现运行时错误 424。需要对象
Dim wbSourceData As Workbook
Dim wbDestination As Workbook
Dim wsSourceData As Worksheet
Dim wsDestination As Worksheet
Dim wsMacros As Worksheet
Dim pvt1 as PivotTable
Dim strFName as String

Set wbDestination = ThisWorkbook
Set wsDestination = wbDestionation.Sheets("Paste Total Here") 'Tab I want data pasted to
Set wsMacros = wbDestination.Sheets("Macros") 'I have a worksheet with dynamic references for my code as the location of the Source Data changes every month

strFName = wsMacros.Range("C107").Value 'The file path to open file

Set wbSourceData = Workbooks.Open(strFName, , ReadOnly:=True)
Set wsSourceData = wbSourceData.Worksheets("Copy From Here") 'Tab I copy data from

With wsSourceData
Set pvt1 = .PivotTables("PivotTable1")
WsDestination.Range("B4") = pvt.GetPivotData("Sum of Dollars","Type","Good","Year Month","2022 March") 'I want to copy Grand Total "Dollars" of the columns "Good" and "2022 March" to be pasted into cell B4 of the worksheet destination sheet of This Workbook
End With

wbSourceData.Close SaveChanges:=False

End Sub


You are declaring your pivot table as one variable, and then trying to reference it as a different one.您将数据透视表声明为一个变量,然后尝试将其引用为不同的变量。

Your declaration: Dim pvt1 as PivotTable您的声明: Dim pvt1 as PivotTable

Your reference: WsDestination.Range("B4") = pvt.GetPivotData("Sum of Dollars","Type","Good","Year Month","2022 March")您的参考: WsDestination.Range("B4") = pvt.GetPivotData("Sum of Dollars","Type","Good","Year Month","2022 March")

Change pvt to pvt1 .pvt更改为pvt1

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

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