Home » excel » Excel VBA Chart Auto Shape Top Left Position

Excel VBA Chart Auto Shape Top Left Position

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a chart in Excel. I’ve added a shape to the chart with:

excelChart.Shapes.AddShape(msoShapeRectangle, 0, 0, excelChart.ChartArea.width, 15)

Chart with shape

I selected the green box and ran the below macro:

Sub Macro6()

    Selection.ShapeRange.Left = 0
    Selection.ShapeRange.Top = 0

End Sub

I was expecting the green box to be positioned flush in the top left of the orange chart area, but as you can see there seems to be some kind of margin before the top/left zero coordinate starts..

How can I programmatically position the green box flush in the corner?

How to&Answers:

Try using IncrementLeft and IncrementTop.

Sub AddBox()
    Dim cht As Chart

    Set cht = Worksheets(1).ChartObjects(1).Chart

    With cht.Shapes.AddShape(msoShapeRectangle, 0, 0, cht.ChartArea.Width, 15)
        .Name = "MyShape"
        .IncrementLeft -5  //Experiment with number to get desired effect
        .IncrementTop -5
    End With
End Sub