Copy data from a Pivot table in one worksheet ot another

痞子三分冷 提交于 2020-06-09 03:02:06

问题


I have two workbooks; in one I have a Pivot table; in the other, an empty worksheet.

I am trying to copy certain data from the pivot table to the other workbook, but it seems like VBA isnt copying my selection.

Currently I have written:

With cevesa.Worksheets("r_hora")

    On Error Resume Next
    .PivotTables("r_hora").PivotFields("PARAM").ClearAllFilters
    .PivotTables("r_hora").PivotSelection = "PARAM['DEM(MW)':'DEM_AGREGADA(MW)','POT(MW)':'POT_HID(MW)','POTDESP(MW)']"
    Selection.Copy

    analisis.Worksheets("DATOS Generación").Range("B1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
    On error goto 0

End with

However, this wont work unless I activate manually the workbook with the Pivot table. It seems to me the selection.copy line is working only for the active workbook, and not pointing at the current Pivotselection.

Thanks!


回答1:


Try the code below, explanations inside the code's comments :

Option Explicit

Sub CopyPivotItemsDataRange()

Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
Dim PvtRng As Range

' set the Pivot-Table object
Set PvtTbl = cevesa.Worksheets("r_hora").PivotTables("r_hora")

' set the Pivot-Table Field object
Set PvtFld = PvtTbl.PivotFields("PARAM")

With PvtFld
    .ClearAllFilters
    ' use Union to merge multipe Pivot Items DataRange
    Set PvtRng = Union(.PivotItems("DEM(MW)").DataRange, .PivotItems("DEM_AGREGADA(MW)").DataRange, _
                .PivotItems("POT(MW)").DataRange, .PivotItems("POT_HID(MW)").DataRange)
End With

PvtRng.Copy

' I let you finish the Paste section

End Sub


来源:https://stackoverflow.com/questions/45634817/copy-data-from-a-pivot-table-in-one-worksheet-ot-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!