在图表上绘制多条线

时间:2016-05-06 13:38:59

标签: excel vba excel-vba plot graph

我正在尝试绘制一个图表,该图表在同一轴上绘制了多个系列。所以我们有:

    Sheet1.ChartObjects(1).Activate
    ActiveChart.ChartType = xlLineMarkers
    Set ChartRange1 = Sheets("Series_2").Range("$E$8:$E20$") 
    ChartRangeAddr1 = ChartRange1.Address(External:=True)
    Set ChartRange2 = Sheets("Series_3").Range("$E$8:$E$20")
    ChartRangeAddr2 = ChartRange2.Address(External:=True)
    (we could have many more here)
    ActiveChart.SetSourceData Source:=Range(ChartRangeAddr1, ChartRangeAddr2)
    ActiveChart.SeriesCollection(1).XValues = "=Series_1!$D$8:$D20"
    ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
    ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
    ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
    ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "USD"
    ActiveChart.Axes(xlCategory).HasMajorGridlines = True

注意:Series_1和Series_2是从不同工作表中获取的数据。出于某种原因,此代码仅在图表上生成系列一。请问,任何人都可以纠正我没有看到的错误,或者指出我的指南针解决了在VBA中绘制多个线条的一般问题。感谢

2 个答案:

答案 0 :(得分:1)

看看你是否可以添加如下行:

ActiveChart.SeriesCollection(1).YValues = "=Series_2!$E$8:$E20$"
ActiveChart.SeriesCollection(2).YValues = "=Series_3!$E$8:$E20$"

我发现当你录制宏时,它有时会跳过重要的步骤。

答案 1 :(得分:1)

SetSourceData仅适用于一张纸上的数据。你可以这样做(跳过ChartRange1Address等):

ActiveChart.SetSourceData Source:=ChartRange1
ActiveChart.SeriesCollection(1).XValues = "=Series_1!$D$8:$D20"
With ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(2).Values = ChartRange2
End With