如何筛选数据透视表,然后计算可见行

时间:2019-05-06 21:39:32

标签: excel vba

我正在开发一个用户窗体,该窗体过滤数据透视表,然后在过滤以显示可用项目后计算多少可见行。

我已经对其进行了正确的过滤,但是有时它会保留以前过滤的别名/选择一个随机的别名进行添加。我真的不知道为什么要这样做,并且我尝试添加一些预防措施。

另一个问题是,当在用户窗体中显示总数时,它要么显示0计数,要么显示值的总数。根据我在网上看到的信息,我认为我正在正确地执行此步骤,而且我不确定从这儿去哪里。它需要显示在数据透视表中可见的确切行数。

Album of Screenshots

Private Sub txtLot1_Change()

Dim pt As PivotTable
Dim pf As PivotField
Dim pf2 As PivotField
Dim pi As PivotItem
Dim strPF As String
Dim strPF2 As String
Dim strPI As String
On Error Resume Next
Dim Available As Integer
Dim OrderMacro As Workbook
Dim SampleSum As Worksheet

Set OrderMacro = ActiveWorkbook
Set SampleSum = OrderMacro.Worksheets("PF Sampling Summary")

'strPromptPF = Alias
'strPromptPI = txtLot1

If Len(txtLot1) >= 2 Then

    Set pt = SampleSum.PivotTables(1)
    strPF = "Alias"
    strPI = txtLot1
    Set pf = pt.PivotFields(strPF)
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    With pf
        .PivotItems(strPI).Visible = True
        .AutoSort xlAscending, .SourceName
        .AutoSort xlManual, .SourceName
        For Each pi In pf.PivotItems
            pi.Visible = False
        Next pi
        .PivotItems(strPI).Visible = True
        .AutoSort xlAscending, .SourceName
    End With

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    Set pf2 = pt.PivotFields("Box #")

    Available = pf2.VisibleItems.Count

    txtAvail1.Value = Available

    Debug.Print txtAvail1

End If


End Sub

我需要发生的最终结果如下:

  1. 用户在用户表单中输入字符。

  2. 当用户窗体看到两个或两个以上字符时,它将过滤数据透视表“别名”字段以使其等于条目。

  3. 用户窗体显示所选别名的行数,该别名在“完成?”中没有条目。字段。

实际发生的最终结果:

  1. 输入正常

  2. 该命令等待两个字符起作用,它过滤别名,但有时在过滤器中显示多个值。

  3. 计数不正确,给出0或所有项目的总数。

1 个答案:

答案 0 :(得分:0)

相反,给它一个镜头-显示数据透视表中的所有项目,然后隐藏没有 strPi的那些项目:

With pf
    .ShowAllItems = True
    .AutoSort xlAscending, .SourceName
    .AutoSort xlManual, .SourceName
    For Each pi In pf.PivotItems
        If pi <> strPi Then pi.Visible = False
    Next pi
    .PivotItems(strPi).Visible = True
    .AutoSort xlAscending, .SourceName
End With