【问题标题】:excel VBA filter pivot table with flexible names具有灵活名称的excel VBA过滤器数据透视表
【发布时间】:2015-07-22 21:41:46
【问题描述】:
Set Weight_wb = Application.Workbooks(WEIGHTFileName).Sheets("TERRY_CAT")
Set pt = Weight_wb .PivotTables("PivotTable4")


With Weight_wb .PivotTables("PivotTable4").PivotFields("Cat")
    .Orientation = xlColumnField
    .Position = 1
End With
With Weight_wb .PivotTables("PivotTable4").PivotFields("Cat")
    .Orientation = xlColumnField
    On Error Resume Next
    .PivotItems("black").Visible = True
    .PivotItems("yellow").Visible = False
    .PivotItems("brown").Visible = False
    .Position = 1
End With

我想将上面的代码更改为更灵活。 我想写一个更通用的子SetCllumnFilter,这样我就可以简单地调用:

SetColumnFilter WEIGHTFileName, "Terry_cat", "PivotTable4", "CAT","black"

类似的东西(它不起作用):

Sub SetPageFilter(WB As String, WS As String, pt As String, fd As String,value as string)
Dim wb_ As Workbook, ws_ As Worksheet, pt_ As PivotTable, fd_ As PivotField

ws_ = Application.Workbooks(WB).Sheets(WS)
pt_ = ws_.PivotTables(pt)
fd_ = pt_.PivotFields(fd)
With fd_
.Orientation = xlPageField
End With
Application.ScreenUpdating = True

Dim i As Long

        .PivotItems(1).Visible = True
        For i = 2 To Field.PivotItems.Count
            If .PivotItems(i).Name = Value Then _
                .PivotItems(i).Visible = True Else _
                .PivotItems(i).Visible = False
        Next i
End Sub

非常感谢!!

【问题讨论】:

  • it doesn't work 不是对问题的有用描述。它怎么不工作?它会给出错误吗?如果有,是哪条线?如果没有错误,代码如何不产生您正在寻找的结果?需要注意的一件事是,PivotItems 集合中必须至少有一个可见项目。当您迭代它们时,这总是很棘手,因为不一定知道哪些是隐藏/可见的。您可以先强制它们全部可见,然后运行您的代码以隐藏它们,如果这是问题的话。

标签: vba excel pivot pivot-table


【解决方案1】:
Sub SetPageFilter(WB As String, WS As String, pt As String, fd As String,value as string)
Dim wb_ As Workbook, ws_ As Worksheet, pt_ As PivotTable, fd_ As PivotField

ws_ = Application.Workbooks(WB).Sheets(WS)
pt_ = ws_.PivotTables(pt)
fd_ = pt_.PivotFields(fd)
With fd_
    .Orientation = xlPageField
End With
Application.ScreenUpdating = True

Dim i As Long

    With fd_
        .PivotItems(.PivotItems.Count).Visible = True
        For i = 1 To .PivotItems.Count
            If .PivotItems(i).Name = Value Then _
                .PivotItems(i).Visible = True Else _
                .PivotItems(i).Visible = False
        Next I
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多