Excel-VBA:在Excel 2010的图表工作表中向系列添加值时出现错误438

问题描述 投票:2回答:1

我正在尝试将一些代码放在一起,从工作表中收集一组数据,然后生成XY散点图。每当它到达用于向系列输入值的行时,它就会产生“运行时错误438:对象不支持此属性或方法”。

xDataRng.Address的价值为"$C$8:$C$11"

我在Win 7上使用Excel 2010。

我查阅了每篇文章,并提供了有关此问题的帮助帖子。我不正确地使用.SeriesCollection.XValues吗?我该如何解决?

谢谢,

Ishwar

Sub createChart()

Set wb = ThisWorkbook
Dim sheetName As Variant, chartName As Variant

sheetName = ActiveSheet.Name

'Find x-axis data
Dim xnameRng As Range, xdataRng As Range
Dim lastCol As Long, lastRow As Long
Dim i As Integer

With ActiveSheet
    lastCol = .Cells(7, .Columns.Count).End(xlToLeft).Column
    Set xnameRng = .Range(Cells(7, 2), Cells(7, lastCol)).Find("Horizontal Position (", lookat:=xlPart)
    lastRow = .Cells(.Rows.Count, xnameRng.Column).End(xlUp).Row
    Set xdataRng = .Range(xnameRng.Offset(1, 0).Address, Cells(lastRow, xnameRng.Column))
End With

'Find y-axis data
Dim ynameRng As Range, ydataRng As Range

With ActiveSheet
    Set ynameRng = .Range(.Cells(7, 2), .Cells(7, lastCol)).Find("Pressure (", lookat:=xlPart)
    Set ydataRng = .Range(ynameRng.Offset(1, 0).Address, .Cells(lastRow, ynameRng.Column))
End With

'Create chart
With wb.Sheets("Chart_Template")
    .Copy After:=Sheets(sheetName)

    chartName = ActiveChart.Name

    'Update chart details
    With wb.Sheets(chartName)
        .SeriesCollection.NewSeries
        .SeriesCollection.XValues(1) = wb.Sheets(sheetName).Range(xdataRng.Address)  FAILS HERE
        .SeriesCollection.Values(1) = wb.Sheets(sheetName).Range(ydataRng.Address)
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).Character.Text = xnameRng.Value
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).Character.Text = ynameRng.Value
    End With
End With

End Sub
excel vba excel-vba
1个回答
2
投票

请尝试以下代码部分替换您的代码:

With wb.Sheets(chartName)
    Dim Ser As Series

    Set Ser = .SeriesCollection.NewSeries
    With Ser
        .XValues = "=" & xDataRng.Address(True, True, xlA1, xlExternal)
        .Values = "=" & yDataRng.Address(True, True, xlA1, xlExternal)
    End With

    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).Character.Text = xnameRng.Value
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).Character.Text = ynameRng.Value
End With
© www.soinside.com 2019 - 2024. All rights reserved.