Pivot Table 根据组合框值过滤

Pivot Table filtering depending on the combobox value

我试图让组合框的值依赖于过滤数据透视 table。如果组合框值与数据透视表 table 的过滤器部分匹配,则下面的代码可以正常工作,但情况并非如此,因此会导致错误。

Private Sub UserForm_Initialize()
ComboBox1.AddItem "3(Facility Approved),4(Bid Appn Approved),12(Cancelled With Outs)"
ComboBox1.AddItem "3"
End Sub
Private Sub CommandButton1_Click()
Call Macro5
Dim sht As Worksheet, pflds As PivotFields, showItems As Boolean
Dim arr

With Worksheets("CT")
    .Range("G1").Value = TextBox2.Value
    .Range("C1").Value = TextBox1.Value
End With
arr = Split(ComboBox1, ",") 'make an array from the combobox value
'show only the values in arr for specific pivot fields
ShowOnlyThese Sheets("BP").PivotTables("PivotTable1").PivotFields("Facility_Status_Id"), arr
ShowOnlyThese Sheets("BC").PivotTables("PivotTable1").PivotFields("Facility_Status_Id"), arr

ActiveWorkbook.RefreshAll
Unload Me
ActiveWorkbook.RefreshAll


End Sub

这是我试图修正该问题但出现错误的代码。任何帮助将不胜感激。

Private Sub UserForm_Initialize()
'list to be chosen in the combobox
ComboBox1.AddItem "3(Facility Approved),4(Bid Appn Approved),12(Cancelled With Outs)"
ComboBox1.AddItem "3"
End Sub
Private Sub CommandButton1_Click()
    Call Macro5
    Dim sht As Worksheet, pflds As PivotFields, showItems As Boolean
    Dim arr

    With Worksheets("Connection Totals")
        .Range("G1").Value = TextBox2.Value
        .Range("C1").Value = TextBox1.Value
    End With
    If ComboBox1.Value = "3(Facility Approved),4(Bid Appn Approved),12(Cancelled With Outs)" Then
    arr = Array("3", "4", "12") 'make an array from the combobox value
    Else
    arr = Array("3")
    'show only the values in arr for specific pivot fields
    ShowOnlyThese Sheets("By Participants").PivotTables("PivotTable1").PivotFields("Facility_Status_Id"), arr
    ShowOnlyThese Sheets("By Corporates").PivotTables("PivotTable1").PivotFields("Facility_Status_Id"), arr
  End If
    ActiveWorkbook.RefreshAll
    Unload Me
    ActiveWorkbook.RefreshAll


End Sub

'loop over all items in a pivotfield shows only those matching a value
Sub ShowOnlyThese(pf As PivotField, arrItems)
    Dim pi As PivotItem, haveOne As Boolean
    For Each pi In pf.PivotItems
        On Error Resume Next
        pi.Visible = Not IsError(Application.Match(pi.Value, arrItems, 0))
        On Error GoTo 0
    Next pi
End Sub

在“即时”窗格中:

? application.match("1", array(1,2,3), 0)     '>> error 2042

? application.match("1",array("1","2","3"),0) '>> 1

您的数据透视字段值是字符串,但您匹配的数组是数字。 如果你传递一个字符串数组,它应该可以正常工作。

你的 ShowOnlyThese 有一个错误,如果隐藏该值意味着没有显示任何值(你必须至少显示一个)

If ComboBox.Value = "3(Facility Approved),4(Bid Appn Approved),12(Cancelled With Outs)" Then
    arr = Array("3", "4", "12")
Else
    arr = Array("3")
End If

ShowOnlyThese Sheets("By Participants").PivotTables("PivotTable1").PivotFields( _
              "Facility_Status_Id"), arr
ShowOnlyThese Sheets("By Corporates").PivotTables("PivotTable1").PivotFields( _
               "Facility_Status_Id"), arr