我需要在Excel中为每张纸创建一个图表。这是我的代码:
Sheets(i).Activate
For Each cht In ActiveSheet.ChartObjects
cht.Delete
Next
'create chart
Set chtChart = ActiveSheet.ChartObjects.Add(Left:=75, Width:=300, Top:=75, Height:=300).Chart
With chtChart
.ChartType = xlXYScatterSmooth
Do While .SeriesCollection.Count <> 0
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
Loop
Set srsNew = .SeriesCollection.NewSeries
With srsNew
.XValues = "='" & Sheets(i).Name & "'!" & _
Sheets(i).Range(Range("K2"), Range("k2").End(xlDown)).Address
.Values = "='" & Sheets(i).Name & "'!" & _
Sheets(i).Range(Range("l2"), Range("l2").End(xlDown)).Address
End With
End With
对于第一张纸,这是有效的,但对于第二张,第三张......它没有。它在XValues或Values中发出错误1004“应用程序定义或对象定义错误”。我还注意到,如果我介绍
range("K2")
在with块之外的我在第二张,第三张....但在第一张中没有错误。
欢迎任何建议
此致
若昂
答案 0 :(得分:4)
Range
。Select
或ActiveSheet
。Dim CurSheet As Worksheet, cht As ChartObject
Dim chtChart As Chart, srsNew As Series
...
Set CurSheet = Worksheets(i)
For Each cht In CurSheet.ChartObjects
cht.Delete
Next
'create chart
Set chtChart = CurSheet.ChartObjects.Add(Left:=75, Width:=300, Top:=75, Height:=300).Chart
With chtChart
.ChartType = xlXYScatterSmooth
Do While .SeriesCollection.Count <> 0
.SeriesCollection(1).Delete
Loop
Set srsNew = .SeriesCollection.NewSeries
With srsNew
.XValues = CurSheet.Range(CurSheet.Range("k2"), CurSheet.Range("k2").End(xlDown))
.Values = CurSheet.Range(CurSheet.Range("l2"), CurSheet.Range("l2").End(xlDown))
End With
End With
答案 1 :(得分:1)
如果你完全符合这样的范围,也许会有所帮助:
With srsNew
.XValues = "='" & Sheets(i).Name & "'!" & _
Sheets(i).Range(Sheets(i).Range("K2"), Sheets(i).Range("k2").End(xlDown)).Address
.Values = "='" & Sheets(i).Name & "'!" & _
Sheets(i).Range(Sheets(i).Range("l2"), Sheets(i).Range("l2").End(xlDown)).Address
End With