制作图表 - 运行时错误424 - 需要对象

时间:2014-09-11 15:05:44

标签: excel excel-vba object graph vba

我正在尝试使用以下VBa代码制作图表。但我在行中得到Run-time error 424 - Object required

Set rngChtXVal = .Columns(1).Offset(1).Resize(.Rows.Count - 1)

出了什么问题?

    Sub MakeGraph()
    Dim myChtObj As ChartObject
    Dim rngChtData As Variant
    Dim rngChtXVal As Variant
    Dim iColumn As Long

    sel= Sheets("Data").Range(Cells(1, 1), Cells(200, 2))
     rngChtData = sel

    ' define chart's X values
    With rngChtData
       Set rngChtXVal = .Columns(1).Offset(1).Resize(.Rows.Count - 1)
    End With

    ' add the chart
    Set myChtObj = ActiveSheet.ChartObjects.Add(Left:=250, Width:=425, Top:=10, Height:=240)
    With myChtObj.Chart

        ' make an XY chart
        .ChartType = xlLine

        ' remove extra series
        Do Until .SeriesCollection.Count = 0
            .SeriesCollection(1).Delete
        Loop

        ' add series from selected range, column by column
        For iColumn = 2 To rngChtData.Columns.Count
            With .SeriesCollection.NewSeries
                .Values = rngChtXVal.Offset(, iColumn - 1)
                .XValues = rngChtXVal
                .Name = rngChtData(1, iColumn)
            End With
        Next

    End With

End Sub

1 个答案:

答案 0 :(得分:0)

您已将rngChtData和rngChtXVal命名为Range个对象,但您已将其声明为Variant。虽然Variants可以是Ranges,但它使得调试代码变得更加困难。尽可能使用显式变量类型。要解决您的问题,请更改以下代码:

Sub MakeGraph()
Dim myChtObj As ChartObject
Dim rngChtData As Range
Dim rngChtXVal As Range
Dim iColumn As Long

With Sheets("Data")
    Set rngChtData = .Range(.Cells(1, 1), .Cells(200, 2))
End With

' define chart's X values
With rngChtData
   Set rngChtXVal = .Columns(1).Offset(1).Resize(.Rows.Count - 1)
End With