我的目的是创建一个数据透视表,并进一步从转储数据(A1:AE170000)中获取数据透视表。我已经在下面添加了我的代码,如果我将数据减少到大约60-65k行,则可以正常工作,但不是这样。
它抛出运行时错误13:在我设置我的数据透视表缓存(PTCache)的行中键入不匹配。
Private Sub OptionButton3_Click()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
ThisWorkbook.Sheets("Data").Activate
Dim PTCache As PivotCache
Dim PT As PivotTable
'Setting range as my entire data set
Dim PTRange As Range
Set PTRange = Range("A1", Range("A1").End(xlToRight).End(xlDown))
'Adding a new worksheet for Pivot Table and Chart
Dim ws As Worksheet
Set ws = Sheets.Add
ws.Name = "All"
PTRange.Select
ThisWorkbook.Sheets("All").Activate
'Runtime error 13:Type Mismatch at this line while setting PTCache
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PTRange)
Set PT = ActiveSheet.PivotTables.Add(PTCache, Range("A1"), "All")
With PT
.PivotFields("Name").Orientation = xlPageField
.PivotFields("Rate").Orientation = xlDataField
.PivotFields("Date").Orientation = xlRowField
End With
PT.PivotSelect ("")
Charts.Add
ActiveChart.Location where:=xlLocationAsObject, Name:=PT.Parent.Name
ActiveChart.ChartType = xlLine
ActiveChart.Parent.Top = Range("I7").Top
ActiveChart.Parent.Left = Range("I7").Left
Range("A2").Select
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
来自PivotCaches.Create Method (Excel)(我的重点):
< blah>< blah> ...作为范围传递时,建议使用字符串指定工作簿,工作表和单元格范围,或者设置命名范围并将名称作为字符串传递。 传递Range对象可能会导致"类型不匹配"意外错误。
只需将字符串var设置为从A1辐射出的数据工作表Range.CurrentRegion property的外部地址,然后使用它。
Option Explicit
Private Sub OptionButton3_Click()
'Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim PT As PivotTable, PTCache As PivotCache
Dim PTRange As Range, ws As Worksheet, strRNG As String
strRNG = ThisWorkbook.Worksheets("Data").Cells(1, 1).CurrentRegion.Address(external:=True)
With Worksheets.Add(after:=Sheets(Sheets.Count))
.Name = "All"
Set PTCache = .Parent.PivotCaches.Create(xlDatabase, strRNG)
Set PT = .PivotTables.Add(PTCache, .Range("A1"), "All")
With PT
.PivotFields("Name").Orientation = xlPageField
.PivotFields("Rate").Orientation = xlDataField
.PivotFields("Date").Orientation = xlRowField
End With
PT.PivotSelect ("")
End With
'all the chart stuff here
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub