簡體   English   中英

如何使用VBA從單元格值控制Excel PIVOT表

[英]How to control Excel PIVOT tables from cell values with VBA

我試圖基於兩個單元格值刷新我的數據透視表。 最終用戶將在單元格B4(區域)中輸入值,並在單元格B5(部門)中輸入值。 數據透視表將根據這些值刷新。

我在下面找到了代碼,但只允許引用1個單元格值。 不知道如何修改2個單元格的值。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    'This line stops the worksheet updating on every change, it only updates when cell
    'B4 or B5 is touched

    If Intersect(Target, Range("B4:B5")) Is Nothing Then Exit Sub

    'Set the Variables to be used
    Dim pt As PivotTable
    Dim Field As PivotField
    Dim NewCat As String

    'Here you amend to filter your data
    Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")
    Set Field = pt.PivotFields("Region")
    NewCat = Worksheets("Sheet1").Range("B4").Value

    'This updates and refreshes the PIVOT table
    With pt
        Field.ClearAllFilters
        Field.CurrentPage = NewCat
        pt.RefreshTable
    End With

End Sub

我能夠使用下面的代碼更新我的數據透視表過濾器。 希望這對其他人有幫助。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'This line stops the worksheet updating on every change, 'it only updates when cell'B4
'or B5 is touched

If Intersect(Target, Range("B4:B5")) Is Nothing Then Exit Sub

'Set the Variables to be used
Dim pt As PivotTable
Dim FieldRegion As PivotField
Dim FieldDept As PivotField
Dim NewRegion As String
Dim NewDept As String

'Amend here to filter your data
Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")
Set FieldRegion = pt.PivotFields("Region")
Set FieldDept = pt.PivotFields("Department")
NewRegion = Worksheets("Sheet1").Range("B4").Value
NewDept = Worksheets("Sheet1").Range("B5").value

'This updates and refreshes the PIVOT table
With pt
FieldRegion.ClearAllFilters
FieldRegion.CurrentPage = NewRegion
FieldDept.ClearAllFilters
FieldDept.CurrentPage = NewDept
pt.RefreshTable
End With

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM