2014-08-27 354 views
1

我编译了VBA代码来过滤数据透视表中的每个名称,然后调用其他子例程来操作和格式化表。这段代码在过去对我来说非常完美,但是在更新源表并对数据透视表进行小的格式更改之后,它现在无法让我了。Excel VBA自动筛选器枢轴表

下面是代码:

Sub AutoFilterEachName() 

Piv_Sht = ActiveSheet.Name 
Sheets(ActiveSheet.Name).Select 
For Each PivotItem In ActiveSheet.PivotTables(1).PageFields(1).PivotItems 
ActiveSheet.PivotTables(1).PageFields(1).CurrentPage = PivotItem.Value 
Call PivotCopyFormatValues 
Call DeleteRows2 
Call DeleteRows2 
Call AddComment 
Call Move_Save_As 

Sheets(Piv_Sht).Select 

Next 
End Sub 

第一:行ActiveSheet.PivotTables(1).PageFields(1).CurrentPage = PivotItem.Value当代码开始不更换过滤器的名称过滤器的第一个值。

第二:例行程序到达Next时,它将转至End Sub,并回到For Each一行。我曾尝试加入Next PivotItem惠特没有结果。所以它通过代码运行一次并停止。

我在死路一条,所以任何帮助表示赞赏。

回答

0

对不起,延迟7个月回应;如果你还需要帮助......我想,这可能会帮助你实现你正在寻找的结果:

Sub AutoFilterEachName() 

    Dim pTbl As PivotTable 
    Dim piv_sht As Worksheet 
    Dim i As Long 

    Set piv_sht = ThisWorkbook.ActiveSheet 
    Set pTbl = piv_sht.PivotTables(1) 

    piv_sht.Select 

    For i = 1 To pTbl.PageFields(1).PivotItems.Count 

     'set the PageField page equal to the name of the PivotItem at index i 
     'if you need to cycle through multiple PageFields, consider a nested For loop or For Each loop 
     pTbl.PageFields(1).CurrentPage = pTbl.PageFields(1).PivotItems(i).Name 

     Call PivotCopyFormatValues 
     Call DeleteRows2 
     Call DeleteRows2 
     Call AddComment 
     Call Move_Save_As 

     piv_sht.Select 

    Next i 

End Sub 

一个原因你For Next不执行,立即将End Sub是因为你的PageFields是空的;如果没有PageFields循环,那么你的循环将立即退出。解决方法是始终确保至少有一个PageField。你可以通过你的For Loop才进入这个代码实现这一点:

pTbl.PivotFields(1).Orientation = xlPageField 

这将在你的表中插入第一PivotFieldPageField