【发布时间】:2014-02-22 02:20:11
【问题描述】:
我正在尝试通过 VBA 创建数据透视图(因此按钮可以根据表单中的动态值创建饼图)
我的代码是:
Dim iRow As Long
'//Find First Empty Row In Database
iRow = Sheets("search results").Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row
Sheets("Custom Chart").visible = True
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Search Results!A3:AM" & iRow, Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Custom Chart!A1", TableName:="PivotTable6" _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Custom Chart").Select
Cells(1, 1).Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Custom Chart!$A$1:$C$18")
ActiveSheet.Shapes("Chart 1").IncrementLeft 192
ActiveSheet.Shapes("Chart 1").IncrementTop 15
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("Ethnicity Of Child"), "Count of Ethnicity Of Child" _
, xlCount
With ActiveSheet.PivotTables("PivotTable6").PivotFields(Me.Dy4.Value)
.Orientation = xlRowField
.Position = 1
End With
ActiveChart.ChartType = xlPie
ActiveChart.ApplyLayout (6)
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Chart Result"
ActiveWorkbook.ShowPivotTableFieldList = False
我的代码在这一行失败:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Search Results!A3:AM" & iRow, Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Custom Chart!A1", TableName:="PivotTable6" _
, DefaultVersion:=xlPivotTableVersion14
说发生了运行时 5 错误。我能想到的唯一原因是我试图使用单元格引用来定义一个范围,我注意到如果你记录创建一个数据透视图,它使用像Sheet1!R1C1 这样的范围,但我不明白这些引用。
任何帮助将不胜感激。
提前致谢。
【问题讨论】:
-
iRow 是 Long 类型,您正在尝试将其添加到字符串中。您需要将
iRow替换为CStr(iRow)。另请查看此主题stackoverflow.com/questions/10714251/…。 -
@DeanBDean 不幸的是,您使用
CStr(iRow)的建议并不能解决问题。此外,在其他地方,我将 iRow 定义为 long 并以相同的方式使用它而不会出现问题。 -
我相信您的问题出在 TableDestination:="Custom Chart!A1" 上。当我用范围对象替换“自定义图表!A1”时,我遇到了运行时 5 错误。在创建数据透视表的行之前,添加
Dim pivotDest as Range。然后在下一行添加Set pivotDest = ActiveWorkbook.Sheets("Custom Chart").Range("A1")。然后将"Custom Chart!A1"替换为pivotDest
标签: excel vba charts pivot-table