在VBA-excel中在一个图上绘制两组数据

时间:2014-11-20 05:05:50

标签: excel vba excel-vba graph

我正在使用VBA for MS-excel 2010.我的任务是从连接到Excel数据电子表格的表单创建图表。基本上,用户选择两家公司,我在表单后面的代码将从电子表格中提取数据,并在同一图表上绘制每个公司的两组数据。纵轴是日期,水平线是货币金额。我的问题在于尝试在同一图表上正确地绘制两组数据。这组值和相应的日期都没有正确的图表。这是我写的(我排除了我认为与问题无关的代码):

dates1 = "$E$2:$E$53"
startSym1 = "$I$2":$I$53" 
dates2 = "$E$522:$E$573"
startSym2 = "$I$522:$I$573"

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=Range( _
"HistoryData!" & dates1 & ",HistoryData!" & startSym1 & ",HistoryData!" & dates2 & ",HistoryData!" & startSym2)

出于某种原因,这仅显示一行?我非常感谢一些帮助,谢谢!  更新:

ActiveSheet.Shapes.AddChart.Select
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = sym1 & " VS. " & sym2
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=Range( _
            "HistoryData!" & dates1 & ",HistoryData!" & startSym1)
Charts(sym1 & " VS. " & sym2).SeriesCollection.Add _
            Source:=Range("HistoryData!" & dates2 & ",HistoryData!" & startSym2)

从建议的链接中,该站点单独使用系列集合属性添加了每个数据集。我在涉及Series集合属性的最后一行有语法错误,这让我觉得我可能错了。

更新:解决了问题!继承人解决方案

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = sym1 & " VS. " & sym2
ActiveChart.SetSourceData Source:=Range( _
            "HistoryData!" & dates1 & ",HistoryData!" & startSym1)
ActiveChart.SeriesCollection.Add _
            Source:=Worksheets("HistoryData").Range(startSym2)

1 个答案:

答案 0 :(得分:0)

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = sym1 & " VS. " & sym2
ActiveChart.SetSourceData Source:=Range( _
        "HistoryData!" & dates1 & ",HistoryData!" & startSym1)
ActiveChart.SeriesCollection.Add _
        Source:=Worksheets("HistoryData").Range(startSym2)

Anwser