2017-04-19 32 views
2

我正在尝试将一些代码从工作表中收集一组数据,然后生成一个XY散点图。只要它到达将值输入到系列中的行,它就会产生“运行时错误438:对象不支持此属性或方法”。Excel-VBA:在图表工作表中向Excel中的系列添加值时出现错误438

xDataRng.Address"$C$8:$C$11"

我使用Excel 2010在Win 7

的值,我抬头一看每一篇文章和帮助线程我能找到这个问题。我错误地使用了.SeriesCollection.XValues吗?我该如何解决它?

谢谢,

Eeshwar

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 

回答

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 
+0

此外,'SeriesCollection.XValues'是一个数组,可以作出= 'xdataRng.Value',但这会使它变成静态的。您的解决方案使其动态链接到范围(y)。 –

+0

@ A.S.H我最近一直使用太多图表和枢轴MACRO;) –

+0

谢谢Shai!这工作完美。 另外,'.Axes(xlCategory,xlPrimary).Character.Text'将不起作用,但'.Axes(xlCategory,xlPrimary).TextTitle.Text'会。 – Eeshwar

相关问题