我正在嘗試使用VBA創建數據透視表,並且我從@Shai Rado獲得了幫助,以便能夠創建一個空的數據透視表,然後添加值字段,當我嘗試再次運行它時,出現以下錯誤:對象變量或塊變量未設置爲「代碼」使用.PivotFields(「MedID」)「Excel VBA運行時錯誤'91'
這對我沒有意義,因爲那部分代碼已經創建了一個空的數據透視表和現在它顯示錯誤。
有什麼想法?我完全陌生的VBA,所以我有很多「傻」的問題。我非常感謝所有幫助!
Option Explicit
Sub Create_Pivot_Table()
Dim wsData As Worksheet, wsPT As Worksheet
Dim PT_Cache As PivotCache
Dim PT As PivotTable
Dim PRng As Range
Dim LastRow As Long
With ThisWorkbook
Set wsData = .Worksheets("Data")
Set wsPT = .Worksheets("Pivot Table")
End With
LastRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row
MsgBox LastRow ' <-- confirm value
Set PRng = wsData.Range("A1:O" & LastRow)
' option 2: Set the Pivot Cache
Set PT_Cache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRng.Address(True, True, xlR1C1, True))
' set the Pivot Table
Set PT = PT_Cache.CreatePivotTable(wsPT.Range("D5"), "Pivot_Table_Test")
With PT
With .PivotFields("MedID")
.Orientation = xlRowField
.Position = 1
.LayoutBlankLine = False
.Subtotals(1) = False
End With
With .PivotFields("TransactionType")
.Orientation = xlColumnField
.Position = 1
.LayoutBlankLine = False
.Subtotals(1) = False
End With
With .PivotFields("Quantity")
.Orientation = xlDataField
.Function = xlCount
.Position = 1
End With
Set PT = Nothing
Set PT_Cache = Nothing
Set wsData = Nothing
Set wsPT = Nothing
Exit Sub
End With
End Sub
好像對象PT爲空。確保這一行:設置PT = CreatePivotTable(....正在返回一個值並設置PT。 – aguertin
也嘗試刪除pivottable作爲第一行代碼(如果存在)。我想知道它不工作的原因是因爲它已經存在 – aguertin
@aguertin如果它存在就不需要刪除'PivotTable',只是爲了檢查它是否是,如果它確實存在,那麼你所需要的就是用更新的'PivotCache'來更新它,如果它不是那麼添加'PivotTable' –