这个excel VBA有时会让我发疯!
我想从此表创建一个数据透视表:
主表
我设法做到了!是的,我得到了数据透视表。但是当我第二次运行代码时,我收到了这个错误:
对象变量或未设置块变量(错误91)
代码:
Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim rawdataSheet As Worksheet
Dim lrow As Long
Set rawdataSheet = Sheets("Financials")
lrow = Cells(Rows.Count, "A").End(xlUp).Row
Dim rng As Range
Set rng = rawdataSheet.Range("A4:R" & lrow)
SrcData = Worksheets("Financials").Name & "!" & rng.Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Worksheets("mypivot2")
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A4").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable78")
pvt.PivotFields("CU").Orientation = xlRowField
pvt.PivotFields("Period").Orientation = xlColumnField
End Sub
错误发生在这一行:
pvt.PivotFields("CU").Orientation = xlRowField
有什么问题?为什么它第一次起作用但不是第二次起作用。
答案 0 :(得分:1)
您第二次运行代码时收到错误消息的原因是因为您已经设置了" PivotTable78" ,所以当您尝试创建它时再次使用相同的名称,您会收到运行时错误。
解决问题的方法是通过"捕捉" pvt
对象,以查看它是否已存在。如果是这样,您只需要使用最新的Pivot Cache刷新Pivot。如果不是,则意味着数据透视表不存在,您需要创建它。
这是通过在以下代码中If pvt Is Nothing Then
之后添加以下行Set pvt = sht.PivotTables("PivotTable78")
来完成的。
Option Explicit
Sub CreatePivotTable()
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim sht As Worksheet
Dim rawdataSheet As Worksheet
Dim rng As Range
Dim lrow As Long
Set rawdataSheet = Sheets("Financials")
With rawdataSheet
lrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A4:R" & lrow)
SrcData = .Name & "!" & rng.Address(ReferenceStyle:=xlR1C1)
End With
' Set "mypivot2" to sht worksheet object >> where the Pivot Table we be located
Set sht = Worksheets("mypivot2")
' range of Pivot Table start location
StartPvt = sht.Name & "!" & sht.Range("A4").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set pvt = sht.PivotTables("PivotTable78")
On Error GoTo 0
If pvt Is Nothing Then
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable78")
pvt.PivotFields("CU").Orientation = xlRowField
pvt.PivotFields("Period").Orientation = xlColumnField
Else
' just refresh the Pivot cache with the updated Range
pvt.ChangePivotCache pvtCache
pvt.RefreshTable
End If
End Sub