Excel VBA:通过变量指定折线图的字段

时间:2013-10-17 12:41:39

标签: vba graph

我需要帮助。我在Excel上创建一个宏来执行不同的图表。 我在图表的VALUES规范中收到错误消息。 由于我需要创建几个具有不同X和Y值的类似图表,因此我通过字符串指定范围,每次都更新其内容。 我正在使用的表格称为“数据”和“图表”,这就是为什么你会在代码中看到这些名称的原因。 我在Excel 2010上使用VBA。

这是代码。

Sub repetutive_charts()

Dim day As Integer
Dim row_in As Long
Dim row_end As Long

row_in = 3602
row_end = 90001

For day = 2 To day = 13
' Need to select an empty cell, like D1, otherwise the old graph is still selected and excel cannot create a new graph

Range("D1").Select
ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(1).name = "=Graph!$A$" & CStr(row_in)
    ActiveChart.SeriesCollection(1).Values = "=Data!$K$" & CStr(row_in) & ":$K$" & CStr(row_end)
    ActiveChart.SeriesCollection(1).Xvalues = "=Data!$I$" & CStr(row_in) & ":$I$" & CStr(row_end)

row_in = row_in + 5400
row_end = row_end + 5400

Next day
End Sub

1 个答案:

答案 0 :(得分:0)

道歉,我犯了一个构思错误,David Zemens让我注意到了。我刚开始用VBA编程,所以我不是语法专家...

Sub repetutive_charts()

Dim day As Integer
Dim row_in As Long
Dim row_end As Long

row_in = 3602
row_end = 90001

For day = 2 To 13
' Need to select an empty cell, like D1, otherwise the old graph is still selected and excel cannot create a new graph

Range("D1").Select
ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(1).name = "=Graph!$A$" & CStr(row_in)
    ActiveChart.SeriesCollection(1).Values = "=Data!$K$" & CStr(row_in) & ":$K$" & CStr(row_end)
    ActiveChart.SeriesCollection(1).Xvalues = "=Data!$I$" & CStr(row_in) & ":$I$" & CStr(row_end)

row_in = row_in + 5400
row_end = row_end + 5400

Next day
End Sub