Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA: Add a scatter chart to worksheet as object

Tags:

excel

vba

charts

I am looking to create a scatter chart that, on button press, creates a scatter chart in Sheet 1 and uses A2:A11 as the x values and B2:B11 as the y values.

Using code at the bottom allows me to create a scatter chart based off of the values in A1:B3 (got this from here). Its close, but not exactly what I'm looking for. How can I tweak this to suit my needs?

I got it set up now so the chart is made, based on the values I want, but I can not get it to appear as an object in Sheet 1. How do I do this? .Location xlLocationAsObject doesn't seem to work.

Private Sub chartButton_Click()
    ActiveWorkbook.Charts.Add
    With ActiveWorkbook.ActiveChart
        'Data?
        .ChartType = xlXYScatter
        .SeriesCollection.NewSeries
        .SeriesCollection(1).Name = "=""Scatter Chart"""
        .SeriesCollection(1).XValues = "=Sheet1!$A$2:$A$11"
        .SeriesCollection(1).Values = "=Sheet1!$B$2:$B$11"

        'Location
        'DON'T KNOW WHAT TO PUT HERE
        '.location xlLocationAsObject doesn't work!

        'Titles
        .HasTitle = True
        .ChartTitle.Characters.Text = "Scatter Chart"
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "X values"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Y values"
        .Axes(xlCategory).HasMajorGridlines = True

        'Formatting
        .Axes(xlCategory).HasMinorGridlines = False
        .Axes(xlValue).HasMajorGridlines = True
        .Axes(xlValue).HasMinorGridlines = False
        .HasLegend = False

    End With
End Sub
like image 816
mandelbug Avatar asked Dec 10 '12 02:12

mandelbug


1 Answers

Your code as written adds a chart as a Chart Sheet, not as a chart on a Worksheet

Try this:

Replace

ActiveWorkbook.Charts.Add
With ActiveWorkbook.ActiveChart

with

Dim sh As Worksheet
Dim chrt As Chart

Set sh = ActiveWorkbook.Worksheets("Sheet1")
Set chrt = sh.Shapes.AddChart.Chart
With chrt

Then you can control its position and size with

    .ChartArea.Left
    .ChartArea.Top 
    .ChartArea.Height
    .ChartArea.Width 
like image 152
chris neilsen Avatar answered Nov 15 '22 08:11

chris neilsen