Insert a Line (shape) using Excel VBA


Inserting shapes using VBA is easy.  Inserting a shape manually looks simple if you need only few. What if you need hundred such shapes?

The problem become more complex if you need them at defined coordinates. For example, if I ask you to draw diagonals of first 50 cells of column A using Straight Line (shape).


Copy-paste and run this program in your vba project.


Sub plotLines()
   Dim shp As Shape

   Set shp = ActiveSheet.Shapes.AddConnector(1,10,20,30,40)
End Sub
 


 Now try this one:
 

Sub plotLines()
Dim shp As Shape
Dim c1 As Range
For x = 1 To 20
    Set c1 = Cells(4, x)
    Set shp = ActiveSheet.Shapes.AddConnector(1, c1.Left, c1.Top, c1.Left + c1.Width, c1.Top + c1.Height)
Next
End Sub



Watch this video tutorial to know more