选择单元格的自动刷新数据透视表Excel

时间:2016-07-05 19:48:05

标签: excel

下午好,

问题:我有一个数据透视表,当它引用的单元格更改值时,它不会自动刷新。因此值在B2:B200中更改,但数据透视表值不会随之更改。

我的一位朋友向我提供了一些代码并且无法正常工作,所以我会分享。

    Public Sub RecalculateSelection()
        Dim rng As Range
        Set rng = Application.Selection
        rng.Calculate
    End Sub

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

扩展我的评论:

如果您希望在更改单元格中的值时更新数据透视表而无需点击功能区中的“数据透视表”刷新按钮,则可以从工作表的pivottable.update事件中触发_Change()

在VBE(Alt + F11)中双击包含在VBAProject中驱动数据透视表的数据的工作表。

Private Sub Worksheet_Change(ByVal Target As Range)
    'change range for which we are detecting a change in this line
    If Not Intersect(Target, Range("B2:B200")) Is Nothing Then
        'Update Pivottables in a specific worksheet:
        Sheets("YourPivotsWorksheetName").PivotTables.Update
    End If
End Sub

现在,如果您更改B2:B200中的单元格,则会更新选项卡“YourPivotsWorksheetName”中的数据透视表。

已更新,可处理多个工作表中的更改

如果您可能实际更改的范围跨多个工作表,则可以使用Workbook_SheetChange()事件。您必须在VBAProject的ThisWorkbook部分执行此操作。

Workbook_SheetChange()附带两个参数。 sh是触发更改的工作表,Target是更改发生的范围。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    'Detect changes only in these sheets
    If instr(1, "Sheet1,Sheet2,Some Other Worksheet", sh.name) Then
        'Detect changes in only this range - Feel free to remove this IF
        If Not Intersect(Target, Range("B2:B200")) Is Nothing Then
            'Update Pivottables in a specific worksheet:
            Sheets("YourPivotsWorksheetName").PivotTables.Update
        End If
    End If
End Sub

以此为起点,您可以了解如何仅在特定工作表中检测更改,而仅检测特定范围。