vba - 如何使用 Excel VBA 2010 创建具有两个数据集的图表

标签 vba excel excel-2010

这实际上是两个不同的问题。首先,我有一个包含三列数据的 Excel 工作表。我在 A、C 和 E 列中有 12 行数据。根据我的查找,该程序应该将 A 列分配给 x 轴,将 C 列和 D 列分配给 y 轴,同时还添加标签。

Sub ChartMaker()
    ActiveWorkbook.Charts.Add
    With ActiveWorkbook.ActiveChart
        .ChartType = xlXYScatterLines
        ActiveChart.SetSourceData Source:=Range("A1:A12,C1:C12,E1:E12")
        .Location xlLocationAsNewSheet
        .HasTitle = True
        .ChartTitle.Characters.Text = "CFL Over Time"
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time (Days)"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "CFL"
        .Axes(xlCategory).HasMajorGridlines = True
        .Axes(xlCategory).HasMinorGridlines = False
        .Axes(xlValue).HasMajorGridlines = True
        .Axes(xlValue).HasMinorGridlines = False
        .HasLegend = False
    End With
End Sub

我不断收到错误“未设置对象变量或 With block 变量”。

这是我的第一个问题!

我的第二个问题是如何使用以下数据集创建图表,其中 y 轴上有两组数据,但它们共享 x 轴。

数据集一:

X     Y1

1    0.87
2    0.45
3    0.92
4    0.03
5    0.99
6    0.45
7    0.63
8    0.83
9    0.28
10   0.66

数据集二:

X      Y2

0.3    2
4.5    3
6      6
7.2    1
7.8    6
8.3    1 
9.1    4
9.6    5
10     9
13     2

有没有办法将它们放在同一个图表上? (当然使用VBA)

最佳答案

创建图表后

ActiveSheet.Shapes.AddChart.Select  
'this adds the chart and selects it in the same statement
ActiveChart.ChartType = xlXYScatter

然后添加第一组点

ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "=Sheet1!$C$1"
ActiveChart.SeriesCollection(1).XValues = "=Sheet1!$A$3:$A$12"
ActiveChart.SeriesCollection(1).Values = "=Sheet1!$C$3:$C$12"

并使用相同的方法添加第二组

ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Name = "Sheet1!$E$1"
ActiveChart.SeriesCollection(2).XValues = "=Sheet1!$D$3:$D$12"
ActiveChart.SeriesCollection(2).Values = "=Sheet1!$E$3:$E$12"

关于vba - 如何使用 Excel VBA 2010 创建具有两个数据集的图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11853197/

相关文章:

excel - 当范围包含特定文本时插入多行

vba - 使用 VBA 选择最后一行并向下复制

excel - 从电源查询中调用 gpkg 上的 sqlite3 时激活 spatialite

excel - 无法在中断模式下执行宏

excel - 根据多个条件应用条件格式

vba - 使用 VBA 在 Office 中压缩图像

vba - VBA 中公共(public)变量的替代方案

vba - Excel - 选择多个单元格时在 VBA 中键入不匹配错误 13

excel - MIN 函数不忽略 FALSE

php - 如何强制 Excel 文件在浏览器中打开而不是下载