【问题标题】:How to Filter Pivot Table and then Count Visible Lines如何过滤数据透视表然后计算可见行
【发布时间】:2019-05-07 15:27:32
【问题描述】:

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

我已经让它正确过滤,但有时它会保留以前过滤的别名/选择一个随机的别名来添加。我真的不知道为什么会这样,我尝试添加一些东西来防止它。

另一个问题是,当在用户窗体中显示总数时,它要么显示计数为 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 或所有项目的总和。

【问题讨论】:

  • 您是否在某处禁用了错误?我认为问题在于您的 For Each pi In pf.PivotItems 循环 - 您不能过滤掉每个数据透视项目...所以您应该留下表格中的最后一个数据透视项目 + 您的 strPi 项目。
  • 嘿 Dwirony,我没有在任何地方禁用错误,我明白你在说什么。我不确定为什么它也没有出错。

标签: excel vba


【解决方案1】:

试一试 - 显示数据透视表中的所有项目,然后隐藏那些不是 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

【讨论】:

  • 嗨 Dwirony,感谢更新代码!它工作得稍微好一些,但仍然在数据透视表中显示多个别名。它似乎发生的频率稍低一些,但它仍在弹出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 2011-09-22
  • 2018-03-31
相关资源
最近更新 更多