![](/img/trans.png)
[英]How to use array values that are dates as XValues on a chart ? (VBA)
[英]How to assign XValues for excel chart using VBA
我具有用于在Excel 2013中绘制图表的VBA功能:
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':
无效的参数
当我单击debug时,它将在上面的函数中标记“ Set .SeriesCollection(1).XValues = XLabels”行。
在文档中写道:
可以将XValues属性设置为工作表上的范围或值的数组,但不能将两者结合使用
因此,它应该能够将给定范围用作XValues的值,但我不明白为什么会出现此错误。
在设置系列的Values和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
您不能为.XValues或.Values使用命名范围,但是可以通过替换系列公式来更改.Formula属性。
有关编辑系列公式的更多信息,请参见http://peltiertech.com/change-series-formula-improved-routines/
请注意,Excel 2013中有一个错误,当您使用VBA更改系列公式时,它会阻止您使用以“ R”或“ C”开头的命名范围; 请参阅http://answers.microsoft.com/zh-cn/office/forum/office_2013_release-excel/named-range-use-in-chart-series-formulas-causes/c5a40317-c33f-4a83-84db-0eeee5c8827f/? auth = 1&rtAction = 1466703182593
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.