VBA 将数据透视表数据复制到列中的下一个空白单元格

VBA Copy Pivot Data to next blank cell in column

已经创建了一个枢轴table,我需要一个宏来从指定的作品sheet (Pivot1) 中获取没有过滤器的枢轴主体数据并将结果复制到下一个空白单元格上的另一个 sheet(选择)。

我已经使用并修改了我在这个网站上找到的下面的内容,但是它没有接收到我的 sheets 并且我收到运行时错误“424” 关于如何执行它有什么想法吗?

Sub PastePivot()

Dim i As Long
Dim LR As Long
Dim j As Long
Dim c As Long
'Find last used row in Pivot1
LR = Pivot1.Cells(Pivot1.Rows.Count, 1).End(xlUp).Row
'Find last used row in Selection
j = Selection.Cells(Selection.Rows.Count, 1).End(xlUp).Row
'Loop through rows on Pivot1
For i = 3 To LR
    'Decide whether to copy the row or not
    If Pivot1.Cells(i, 1).Value <> "0" Then
        'Update pointer to the next unused row in Selection
        j = j + 1
        'Only copy used columns, to stop it thinking every cell in the
        'destination row is "used"
        c = Pivot1.Cells(i, Pivot1.Columns.Count).End(xlToLeft).Column
        'Copy the values (without using Copy/Paste via the clipboard)
        Selection.Rows(j).Resize(1, c).Value = Pivot1.Rows(i).Resize(1, c).Value
    End If
Next i

结束子

如果你想得到一个枢轴的主体 table 使用它的 DataBodyRange 属性。

下面的代码假定您在 'Sheet1' 上有 1 个数据透视表 table,并且您想将其复制到 'Sheet2'。

Sub CopyPivotBody()
Dim ws As Worksheet
Dim pt As PivotTable
Dim rngBody As Range

    Set ws = Sheets("Sheet1")
    Set pt = ws.PivotTables(1)
    Set rngBody = pt.DataBodyRange
    
    rngBody.Copy Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)
    
End Sub

请注意,如果这不能为您提供您想要的确切范围,您可以 offset/resize 像任何其他范围一样。