Private Sub CommandButton1_Click()
Dim filterText As String
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws As Worksheet
Dim pt As PivotTable
Dim pc As PivotCache
Dim cfB As CubeField
' 定義工作表與範圍
Set ws1 = ThisWorkbook.Sheets("ws1")
Set ws2 = ThisWorkbook.Sheets("ws2")
' 讀取篩選文字
filterText = ws1.OLEObjects("Textbox1").Object.Text
' 創建樞紐分析表快取
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:=ThisWorkbook.Connections("pi1"))
' 檢查是否成功設置 PivotCache
If pc Is Nothing Then
MsgBox "無法設置現有的 PivotCache。"
Exit Sub
End If
' 設定樞紐分析表
Set ws = Worksheets("ws2")
Set pt = ws.PivotTables("LKK")
' 設置欄位A
Set cfB = pt.CubeFields("[ex].[A]") ' 欄位名稱為 "A"
cfB.Orientation = xlRowField
pt.PivotFields(1).Subtotals(1) = False
' 設置欄位B
Set cfB = pt.CubeFields("[ex].[B]") ' 欄位名稱為 "B"
cfB.Orientation = xlRowField
pt.PivotFields(2).Subtotals(1) = False
' 設置欄位C
Set cfB = pt.CubeFields("[ex].[C]") ' 欄位名稱為 "C"
cfB.Orientation = xlRowField
pt.PivotFields(3).Subtotals(1) = False
' 篩選樞紐分析表資料
' On Error Resume Next
cfB.ClearAllFilters
cfB.PivotFilters.Add Type:=xlCaptionContains, Value1:=filterText
'On Error GoTo 0
' 更新樞紐分析表顯示
pt.RefreshTable
' 完成設置
Set pt = Nothing
Set cfB = Nothing
Set pc = Nothing
Set ws1 = Nothing
Set ws2 = Nothing
End Sub
cfB.ClearAllFilters
cfB.PivotFilters.Add Type:=xlCaptionContains, Value1:=filterText
cfB.ClearAllFilters and cfB.PivotFilters.Add Type:=xlCaptionContains, Value1:=filterText in this code are used to filter fields in the pivot analysis table. When you execute this code, you may encounter errors, usually because the program cannot find the pivot table column named [ex].[A], [ex].[B], or [ex].[C] bit, or the filter conditions are set incorrectly.
New contributor
流浪小白 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.