简体   繁体   中英

How to create a chart that has two data sets using Excel VBA 2010

This is really two separate questions. First, I have an excel sheet with three columns of data. I have 12 rows of data in columns A, C, and E. From what I've been looking up, This program should assign column A to the x-axis, and Columns C and D to the y-axis, while also adding labels.

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

I keep getting the error "Object variable or With block variable not set".

That's my first question!

My second question is how can I create a graph with the following sets of data, where there are two sets of data on the y-axis, but they share an x-axis.

Data set one:

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

Data set two:

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

Is there a way to get these on the same graph? (Using VBA of course)

After creating the chart

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

you then add the first set of points

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"

and use the same method to add the second set

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM