Home » excel » excel – Swapping axes plotting Scatter chart in VBA

excel – Swapping axes plotting Scatter chart in VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

Using the following code I get the graph I want exactly as I want it except that it plots the axes the wrong way round. How do I get it to change the X data to Y data and vice versa?

    Sub AddChartObject()


    Set cht = ActiveChart
    Set rng = ActiveSheet.Range("AB30:AD40")



    With ActiveSheet.ChartObjects.Add(Left:=rng.Left, Width:=rng.Width, Top:=rng.Top, Height:=rng.Height)
     '(Left:=100, Width:=375, Top:=75, Height:=225)
        .Chart.ChartType = xlXYScatterLines

        .Chart.SetSourceData Source:=Range("O30:O40,N30:N40")


    End With


End Sub
How to&Answers:

You need to set the XValues and Values independently, after you add the data to the chart.

Dim srs as Series

With ActiveSheet.ChartObjects.Add(Left:=rng.Left, Width:=rng.Width, Top:=rng.Top, Height:=rng.Height)
 '(Left:=100, Width:=375, Top:=75, Height:=225)
    .Chart.ChartType = xlXYScatterLines

    '.Chart.SetSourceData Source:=Range("O30:O40,N30:N40")
    Set srs = .Chart.SeriesCollection.NewSeries
    srs.Name = "The series name" '<-- edit as needed
    srs.XValues = Range("O30:O40")
    srs.Values = Range("N30:N40")

End With

If that doesn’t do it, then just flip the Values/xValues like:

    srs.XValues = Range("N30:N40")
    srs.Values = Range("O30:O40")

One of these methods will do it for you.