Finance

Charts

Statistics

Macros

Search

Rectangle In Excel VBA

The following example demonstrates how to create a rectangle with fill color, border line, and rotation. A rectangle is a shape of the type msoShapeRectangle.

Sub CreateRectangle()
    Dim Sh As Shape
    ThisWorkbook.Worksheets("Sheet3").Activate
    Set Sh = ActiveSheet.Shapes.AddShape(msoShapeRectangle, 30, 30, 50, 80)
    Sh.Fill.ForeColor.RGB = RGB(255, 0, 0)
    Sh.Line.ForeColor.RGB = RGB(255, 255, 0)
    Sh.Line.Weight = 3
    Sh.Rotation = 20
    Set Sh = Nothing
End Sub

Explanation:
The AddShape() method is used to create many different types of graphic objects. It takes five parameters:

  • Type: A value from the enumeration msoAutoShapeType. This enumeration includes well over 100 elements, each representing a specific type of graphic object. By specifying msoShapeRectangle, you create a rectangle.
  • Left and Top: These specify the coordinates of the bounding frame of the new shape, measured from the top-left corner of the worksheet.
  • Width and Height: These define the width and height of the bounding frame. For a rectangle, the bounding frame corresponds exactly to the shape itself. For an oval, however, the bounding frame is the invisible rectangle surrounding the oval, which becomes visible when the shape is selected.

The Fill property of a shape controls the fill formatting. Here, the sub-property ForeColor.RGB is used to set the fill color of the shape.

The Line property pertains to the line formatting of the shape. For line shapes, it controls the line itself; for larger shapes like a rectangle, it controls the border line. Here, the sub-property ForeColor.RGB sets the border color.

The Weight property sets the thickness of the border line.

The Rotation property determines the rotation angle of the graphic object in degrees, measured clockwise.

Note:
The coordinates of the shape (Left and Top) do not change when the shape is rotated, even though, for example, the position of the upper-left corner of the shape may appear shifted. Therefore, the actual position of the shape on the worksheet is determined only by the combination of Left, Top, and Rotation values.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx