如何使用 VBA 为 excel 图表分配 XValue

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)

我收到一个错误:

Runtime Error '1004':

Invalid Parameter

当我单击调试时,它会在上面的函数中标记行 "Set .SeriesCollection(1).XValues = XLabels"。

文档中写着:

The XValues property can be set to a range on a worksheet or to an array of values, but it cannot be a combination of both

所以它应该可以将给定的范围作为XValues的值,但是我不明白为什么会出现这个错误。

在设置系列的值和 X 值之前,您需要先添加系列。使用 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/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