我有这个VBA函数用于在Excel 2013中绘制图表:
Sub DrawChart2(obj_worksheetTgt As Worksheet, ByVal XLabels As Range, ByVal DataValues As Range, ByVal chartTitle As String, a As Integer, b As Integer)
'
'obj_worksheetTgt - Object worksheet on which to be placed the chart
'XLabels - Data range for X labels
'DataValues - Data range for Y values
'chartTitle - Chart title
'a - left border position of chart in pixels
'b - top border position of chart in pixels
With obj_worksheetTgt.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
Set .SeriesCollection(1).XValues = XLabels ' Here is the error
Set .SeriesCollection(1).Values = DataValues
.Legend.Position = -4107
.HasTitle = True
.chartTitle.Text = chartTitle
.chartTitle.Font.Size = 12
With .Axes(1).TickLabels
.Font.Size = 8
.Orientation = 90
End With
End With
End With
End Sub
我用这种方式调用函数:
ChartsWorksheet = "Summary"
Queryname = "query1"
chartTitle = "Values"
With .Worksheets("LastDayData").ListObjects(Queryname)
Set chart_labels = .ListColumns(2).DataBodyRange
Set chart_values = .ListColumns(6).DataBodyRange
End With
Call DrawChart2(.Worksheets(ChartsWorksheet), chart_labels, chart_values, chartTitle, 10, 10)
我收到一个错误:
运行时错误'1004':
无效参数
当我点击调试时,它会在上面的函数中标记“Set .SeriesCollection(1).XValues = XLabels”行。
在文档中写道:
XValues属性可以设置为工作表上的范围或 值数组,但它不能是两者的组合
因此它应该能够将给定范围作为XValues的值,但我无法理解为什么会出现此错误。
答案 0 :(得分:5)
在设置系列的值和XValues之前,您需要先添加系列。使用SeriesCollection.NewSeries
方法很容易做到,如下所示:
With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
' need to add the series before you can assign the values/xvalues
' calling the "NewSeries" method add one series each time you call it.
.SeriesCollection.NewSeries
' now that the series is added, you may assign (not set) the values/xvalues
.SeriesCollection(1).XValues = XLabels
.SeriesCollection(1).Values = DataValues
End With
End With
答案 1 :(得分:-1)
您不能对.XValues或.Values使用命名范围,但可以通过替换系列公式来更改.Formula属性
有关编辑序列公式的详细信息,请参阅http://peltiertech.com/change-series-formula-improved-routines/
请注意,Excel 2013中存在一个错误,当您使用VBA更改系列公式时,它会阻止您使用以“R”或“C”开头的命名区域;见http://answers.microsoft.com/en-us/office/forum/office_2013_release-excel/named-range-use-in-chart-series-formulas-causes/c5a40317-c33f-4a83-84db-0eeee5c8827f/?auth=1&rtAction=1466703182593