剪切特定的单元格,刷新枢轴,然后在枢轴后粘贴单元格

时间:2019-04-05 18:17:12

标签: excel vba

我在数据透视表之后放置了三行数据。我正在尝试创建一个流程来在刷新数据透视表之前剪切该数据,然后在刷新数据透视表之后进行粘贴。数据透视表占据列B-1,单元格占据相同的列。在数据透视表的末端和三行数据之间有一排分隔线。

1 个答案:

答案 0 :(得分:0)

好吧,这是棘手的事情之一,因为您需要知道刷新后 会变大,但您需要之前知道刷新。

我认为您最好在数据和数据透视表之间插入一堆行,安全地刷新数据透视表,然后删除多余的行。

Sub RefreshButPreserveFooterRows()

    Dim pt As PivotTable
    Dim PivotOriginalEndPosition As Integer
    Dim PivotRefreshedEndPosition As Integer
    Dim safetyGap

    'pick how many rows you want to insert.  Might as well be generous.
    safetyGap = 100
    Set pt = ActiveSheet.PivotTables("PivotTable1")

    'Deterimine the position of the first row after your pivot table prior to refresh
    PivotOriginalEndPosition = pt.RowRange.Rows.Count + pt.RowRange.Row

    'Insert howerver many rows you specified as "Safety Gap" between your pivot and your data
    Rows(PivotOriginalEndPosition & ":" & PivotOriginalEndPosition + safetyGap).Insert Shift:=xlDown

    'refresh the pivot
    pt.RefreshTable

    'Deterimine the position of the first row after your pivot table after to refresh
    PivotRefreshedEndPosition = pt.RowRange.Rows.Count + pt.RowRange.Row

    'delete the extra rows from the safety gap, accounting for the new size of the pivot table
    Rows(PivotRefreshedEndPosition & ":" & PivotOriginalEndPosition + safetyGap).Delete

End Sub