VBA for Excel 2007 tutorial-insert shapes in Excel sheet


VBA code to insert shapes in Excel sheet

In this example, you will learn VBA code to add shapes in to your current Excel worksheet. A shape is a member of the Shapes collection. To add a shape to Excel worksheet, the AddShape() method is used. The addShape() method has the following prototype:

AddShape(Shape_type, Left,Top,Width,Height)

-The Shape_type argument represents the type of shape to be added to the Excel sheet. It can be msoShapeArc, msoShapeCube, msoShapeDiamond, msoShapeHeart, msoShapeRectangle, etc.
-Left, Top, Width, and Height represent the value of x-coordinate, y-coordinate, width, and height of the shape that will be displayed in the Excel sheet.

To run this example VBA code, you will need a Form, and a CommandButton.


VBA for Excel: vba example code to insert shapes in excel sheet
VBA code for this example:


Private Sub CommandButton1_Click()
  'Add a a simple green heart shape in Excel worksheet
  Worksheets(1).Shapes.AddShape msoShapeHeart, 50, 50, 200, 200
  With Worksheets(1).Shapes(1)
    .Fill.ForeColor.RGB = RGB(0, 255, 0)
    .Line.DashStyle = msoLineSolid
  End With

  'Add a heart shape with gradient fill  in Excel worksheet
  Worksheets(1).Shapes.AddShape msoShapeHeart, 100, 100, 200, 200
  With Worksheets(1).Shapes(2)
    .Line.DashStyle = msoLineDashDot
    .Fill.PresetGradient msoGradientHorizontal, 1, msoGradientFire
  End With 

  'Add a cube shape with gradient fill in Excel worksheet
   Worksheets(1).Shapes.AddShape msoShapeCube, 250, 100, 200, 200
  With Worksheets(1).Shapes(3)
    .Line.DashStyle = msoLineSolid
    .Fill.PresetGradient msoGradientDiagonalDown, 1, msoGradientSilver
   
  End With
   
End Sub

Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.