【问题标题】:Pivot Table Field has no items数据透视表字段没有项目
【发布时间】:2016-12-14 01:06:45
【问题描述】:

我正在处理 Excel 上的一系列数据透视表,我希望通过以下方式自动执行特定过滤器:用户在一个单元格中输入特定值,工作簿中的所有过滤器都会相应刷新.我一直在阅读 Stack Exchange 中的帖子,其中解释了如何做到这一点。但是,我遇到了一个我无法解决的问题。

我的数据来自外部 Microsoft Access 数据库。我在数据库和 Excel 文件之间创建了一个连接;数据被导入到 Excel 文件中,并在其中显示为表格tblExcel。然后我的数据透视表链接到这个tblExcel

要刷新过滤器,我想使用以下行:

item.Visible = (item.Caption = cd)

其中itemPivotItems 对象,cd 是用户输入的值。这行不工作,所以我写了下面的子程序来检查一些东西:

Sub Test()

check = 0

For Each field In Application.ActiveWorkbook.Worksheets("Sheet1").PivotTables("PivotTable").PivotFields("[tblExcel].[Field1].[Field1]").PivotItems
    check = check + 1
Next

MsgBox check

End Sub 

事实证明,对于我的所有字段,MsgBox 总是返回 0,就像它们是空的一样。

有人知道为什么会这样吗?是因为我的数据模型结构吗?我该如何规避它?

【问题讨论】:

  • 您要过滤哪个数据透视字段名称?
  • 那个叫"[tblExcel].[Field1].[Field1]"
  • [tblExcel] 是您的源数据,对吧?您正在尝试过滤该来源中的Field1 吗?
  • 是的,我将 Access 中的数据作为表格导入。然后将表链接到 Access 数据库。表格本身在 Excel 中。

标签: excel vba ms-access pivot-table


【解决方案1】:

尝试以下代码,出于调试目的,您有一个 InputBox,您可以在其中写下您希望 PIVOT 表过滤到的 Field1 值。 p>

Option Explicit
Public Sub Filter_PivotTable_Items()

Dim PvtTbl                              As PivotTable
Dim pvtFld                              As PivotField
Dim cd                                  As String

' setting the Pivot Table to a PivotTable Object
Set PvtTbl = ActiveWorkbook.Worksheets("Sheet1").PivotTables("PivotTable")

Application.ScreenUpdating = False

' set Pivot table to show only the selected Project's Data
Set pvtFld = PvtTbl.PivotFields("Field1")

' select manually the value for Field 1 >> for debug purpose
cd = InputBox("Select Item")
Call SelectPivotItem(pvtFld, cd)

End Sub


Public Sub SelectPivotItem(Field As PivotField, cd As String)

Dim Item                            As PivotItem

On Error GoTo cd_Error
For Each Item In Field.PivotItems
    Item.Visible = (Item.Caption = cd)
Next

cd_Error:
If Err.Number = 1004 Then
    MsgBox "Item " & cd & " not found !"
    Exit Sub
End If

End Sub

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 2021-12-06
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多