是,我已经搜索了此问题,但没有找到可以解决错误的解决方案。
我的程序的目标是从数据表(ws)生成数据透视表,并从该数据透视表创建数据透视图。这将是同事使用的宏,因此我希望它即使在更恶劣的情况下也可以工作(这就是为什么我经常引用单元格而不是简单的字符串,最终用户可以更改字符串,然后程序会坏)这个程序中有很多错误,但是我能够修复大多数错误。
保持返回的唯一一个错误是“运行时错误'5':无效的过程调用或参数”。对于此代码
Set pt = ws_pivot.PivotTables.Add( _
PivotCache:=pc, _
TableDestination:="'" & ws_pivot.Name & "'!" & ws_pivot.Range("A1").Address, _
TableName:="pt" & Str(ActiveWorkbook.PivotTables.Count))
在子例程中
Option Explicit
Sub VbaPivotReport2()
Dim pc As PivotCache
Dim pt As PivotTable
Dim ws As Worksheet 'Source worksheet, with data
Dim ws_pivot As Worksheet 'worksheet with PivotTable
Dim ch_pivot As Chart
Dim sh As Shape
Set ws = Worksheets("Waiting List Members")
'This checks for pre-existing pivot caches, creating a new one if there aren't any
If ThisWorkbook.PivotCaches.Count = 0 Then
Set pc = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:="'" & ws.Name & "'!" & ws.Range("A1").CurrentRegion.Address, _
Version:=xlPivotTableVersion15)
Else
Set pc = ThisWorkbook.PivotCaches(1)
End If
Set ws_pivot = Worksheets.Add
'Concatenating the name with a count makes each one unique, so there aren't duplicates
ws_pivot.Name = "Pivot_Report" & Str(Worksheets.Count - 1)
Set pt = ws_pivot.PivotTables.Add( _
PivotCache:=pc, _
TableDestination:="'" & ws_pivot.Name & "'!" & ws_pivot.Range("A1").Address, _
TableName:="pt" & Str(ActiveWorkbook.PivotTables.Count))
With pt.PivotFields("Length")
.Orientation = xlRowField
.Position = 1
End With
pt.AddDataField _
pt.PivotFields("MonthsWaiting"), _
Caption:="Avg Months Waiting", _
Function:=xlAverage
'Below here is all formatting the PivotChart, making it look nice
pt.CompactLayoutRowHeader = "Length"
Range("A2").Group _
Start:=True, _
End:=True, _
By:=1
Range("A1").CurrentRegion.NumberFormat = "0.0"
Set sh = ws_pivot.Shapes.AddChart2( _
Style:=201, _
XlChartType:=xlColumnClustered)
ch_pivot = sh.Chart
ch_pivot.SetSourceData Source:=(ws_pivot.Range("A1").CurrentRegion)
ch_pivot.Legend.Delete
ch_pivot.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
Selection.Caption = "Boat Length Overall (LOA)"
ch_pivot.SetElement (msoElementChartTitleAboveChart)
Selection.Caption = "LOA vs Average Months Waiting"
With ch_pivot.Axes(xlValue)
.TickLables.NumberFormat = "0"
.MajorUnit = 10
End With
With ch_pivot.FullSeriesCollection(1).Points(1).Format.Fill
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorAccent2
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0.6000000238
.Transparency = 0
.Solid
End With
End Sub
我看到的解决方案是DestinationName如果包含空格,则需要用撇号代替:我的不需要。我也尝试过通过
设置表变量Set pt = pc.CreatePivotTable(Destination, [Name], etc...)
我得到同样的错误。 任何帮助表示赞赏。