错误"参数无效"创建包含两个系列

时间:2018-02-27 04:35:39

标签: excel vba charts

我在尝试使用excel中的宏创建图表时遇到错误这是我正在尝试的

Dim mychart As Chart
Set mychart = ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth).Chart

Dim objCht As ChartObject
Dim Tplot As Range ' T in x axis
Dim Pplot As Range ' P in y axis

Set objCht = ActiveSheet.ChartObjects(1)

Set Tplot = Range("W8:W" & Tendcell)
Set Pplot = Range("X8:X" & Tendcell)
Set Zplot = Range("Y8:Y" & Tendcell)
With objCht.Chart
    .SeriesCollection(1).XValues = Tplot
    .SeriesCollection(1).Values = Pplot
    .SeriesCollection(2).XValues = Tplot
    .SeriesCollection(2).Values = Zplot


End With

我收到错误:参数无效

如何指定数据所属的系列?

1 个答案:

答案 0 :(得分:0)

在尝试设置值之前,您需要先添加系列。另外,使用顶部的Option Explicit来检查变量声明。你有一些遗漏,包括你没有声明/定义TendCell,所以我把它设置为12。

Option Explicit

Public Sub test()

    Dim mychart As Chart
    Set mychart = ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth).Chart

    Dim objCht As ChartObject
    Dim Tplot As Range                           ' T in x axis
    Dim Pplot As Range                           ' P in y axis
    Dim Zplot As Range

    Set objCht = ActiveSheet.ChartObjects(1)

    Dim TendCell As Long
    TendCell = 12

    With ActiveSheet
        Set Tplot = .Range("W8:W" & TendCell)
        Set Pplot = .Range("X8:X" & TendCell)
        Set Zplot = .Range("Y8:Y" & TendCell)
    End With

    With objCht.Chart

        .SeriesCollection.NewSeries
        .SeriesCollection(1).XValues = Tplot
        .SeriesCollection(1).Values = Pplot
        .SeriesCollection.NewSeries
        .SeriesCollection(2).XValues = Tplot
        .SeriesCollection(2).Values = Zplot


    End With

End Sub