我试图在excel工作簿中循环,以便在每个工作表上创建相同的数据透视表,但每个工作表在相同的列中包含不同的数据。数据透视表可以工作,但循环在完成第一个工作表后停止。
有没有人有建议让循环遍历所有工作表?
Sub PivotTableLoop()
Dim FinalRow            As Long
Dim DataSheet           As String
Dim PvtCache            As PivotCache
Dim PvtTbl              As PivotTable
Dim DataRng             As Range
Dim TableDest           As Range
Dim ws                  As Worksheet
Dim wb                  As Workbook
Set wb = ActiveWorkbook
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
'Beginning of Loop
For Each ws In ActiveWorkbook.Worksheets
'set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 8))  ' conversion of R1C1:R & FinalRow & C8
'set range for Pivot table placement
Set TableDest = Sheets(DataSheet).Cells(1, 9)  ' conversion of R1C9
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, DataRng)
'this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables("PivotTable4") ' check if "PivotTable4" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' "PivotTable4" doesn't exist >> create it
'create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables.Add(PivotCache:=PvtCache, TableDestination:=TableDest, TableName:="PivotTable4")
With PvtTbl.PivotFields("Document Type")
    .Orientation = xlRowField
    .Position = 1
End With
With PvtTbl.PivotFields("Accounting Event")
    .Orientation = xlRowField
    .Position = 2
End With
With PvtTbl.PivotFields("Document Number")
    .Orientation = xlRowField
    .Position = 3
End With
PvtTbl.AddDataField ActiveSheet.PivotTables( _
"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
    ActiveCell.Offset(1, 0).Range("A1").Select
PvtTbl.PivotFields("Document Type").ShowDetail _
    = False
ActiveCell.Offset(-1, 0).Range("A1").Select
PvtTbl.CompactLayoutRowHeader = _
    "JIFMS Document Types"
ActiveCell.Offset(2, 1).Range("A1").Select
PvtTbl.PivotSelect "", xlDataAndLabel, True
PvtTbl.DataPivotField.PivotItems( _
    "Sum of Amount").Caption = "JIFMS Sum of Amounts"
ActiveCell.Offset(5, 0).Range("A1").Select
Else  
'just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTableenter code here
End If
Next ws
End Sub发布于 2016-08-26 00:59:02
首先,学习缩进你的代码。当所有代码块的内容都在第1列时,阅读代码会让人头晕目眩。难以阅读的代码就是难以调试的代码。
获取VBE外接程序。如果您使用的是32位Office,则可以使用智能缩进器为您执行此操作。如果你使用的是64位的Office,你可以使用最新的MZ-Tools (我认为是$$$),或者是免费的开源Rubberduck (免责声明,我一直都在使用)- v2.x (仍在测试阶段)包含了智能缩进器的大部分特性。
还要去掉像下面这样的烦人和无用的行续写:
PvtTbl.PivotFields(“文档类型”).ShowDetail_= False
/rant
您不会在第一次迭代后将PvtTbl设置回Nothing,因此,假设在第一次迭代中分配了引用一次之后,整个If...End If块将不会运行。
通过将循环体提取到自己的过程中(从而使PvtTbl实质上限定在循环体的范围内),您就消除了这个问题并增强了代码的可读性。这个操作被称为“提取方法”重构。
您还迭代了活动工作簿中的所有工作表,但是在循环体中的任何地方都没有使用ws,所以一切都在活动工作表之外工作……这可能不是你想要的。
https://stackoverflow.com/questions/39149723
复制相似问题