Vba add shape word

Adds an AutoShape to a drawing canvas. Returns a Shape object that represents the AutoShape and adds it to the CanvasShapes collection.

expression.AddShape(Type, Left, Top, Width, Height)

expression    Required. An expression that returns a CanvasShapes object.

Type   Required Long. The type of shape to be returned. Can be any MsoAutoShapeType
constant.

MsoAutoShapeType can be one of these MsoAutoShapeType constants.
msoShapeFlowchartDirectAccessStorage
msoShapeFlowchartDocument
msoShapeFlowchartInternalStorage
msoShapeFlowchartManualInput
msoShapeFlowchartMerge
msoShapeFlowchartOffpageConnector
msoShapeFlowchartPredefinedProcess
msoShapeFlowchartProcess
msoShapeLeftBracket
msoShapeFlowchartConnector
msoShapeFlowchartData
msoShapeFlowchartDecision
msoShapeFlowchartDelay
msoShapeFlowchartDisplay
msoShapeFlowchartExtract
msoShapeFlowchartMagneticDisk
msoShapeFlowchartManualOperation
msoShapeFlowchartMultidocument
msoShapeFlowchartOr
msoShapeFlowchartPreparation
msoShapeFlowchartPunchedTape
msoShapeFlowchartSequentialAccessStorage
msoShapeFlowchartSort
msoShapeFlowchartStoredData
msoShapeFlowchartSummingJunction
msoShapeFlowchartTerminator
msoShapeFoldedCorner
msoShapeHeart
msoShapeHexagon
msoShapeHorizontalScroll
msoShapeIsoscelesTriangle
msoShapeLeftArrow
msoShapeLeftArrowCallout
msoShapeLeftBrace
msoShapeLeftRightArrow
msoShapeLeftRightArrowCallout
msoShapeLeftRightUpArrow
msoShapeLeftUpArrow
msoShapeLightningBolt
msoShapeLineCallout1
msoShapeLineCallout1AccentBar
msoShapeLineCallout1BorderandAccentBar
msoShapeLineCallout1NoBorder
msoShapeLineCallout2
msoShapeLineCallout2AccentBar
msoShapeLineCallout2BorderandAccentBar
msoShapeLineCallout2NoBorder
msoShapeLineCallout3
msoShapeLineCallout3AccentBar
msoShapeLineCallout3BorderandAccentBar
msoShapeLineCallout3NoBorder
msoShapeLineCallout4
msoShapeLineCallout4AccentBar
msoShapeLineCallout4BorderandAccentBar
msoShapeLineCallout4NoBorder
msoShapeMixed
msoShapeMoon
msoShapeNoSymbol
msoShapeNotchedRightArrow
msoShapeNotPrimitive
msoShapeOctagon
msoShapeOval
msoShapeOvalCallout
msoShapeParallelogram
msoShapePentagon
msoShapePlaque
msoShapeQuadArrow
msoShapeQuadArrowCallout
msoShapeRectangle
msoShapeRectangularCallout
msoShapeRegularPentagon
msoShapeRightArrow
msoShapeRightArrowCallout
msoShapeRightBrace
msoShapeRightBracket
msoShapeRightTriangle
msoShapeRoundedRectangle
msoShapeRoundedRectangularCallout
msoShapeSmileyFace
msoShapeStripedRightArrow
msoShapeSun
msoShapeTrapezoid
msoShapeUpArrow
msoShapeUpArrowCallout
msoShapeUpDownArrow
msoShapeUpDownArrowCallout
msoShapeUpRibbon
msoShapeUTurnArrow
msoShapeVerticalScroll
msoShapeWave
msoShape16pointStar
msoShape24pointStar
msoShape32pointStar
msoShape4pointStar
msoShape5pointStar
msoShape8pointStar
msoShapeActionButtonBackorPrevious
msoShapeActionButtonBeginning
msoShapeActionButtonCustom
msoShapeActionButtonDocument
msoShapeActionButtonEnd
msoShapeActionButtonForwardorNext
msoShapeActionButtonHelp
msoShapeActionButtonHome
msoShapeActionButtonInformation
msoShapeActionButtonMovie
msoShapeActionButtonReturn
msoShapeActionButtonSound
msoShapeArc
msoShapeBalloon
msoShapeBentArrow
msoShapeBentUpArrow
msoShapeBevel
msoShapeBlockArc
msoShapeCan
msoShapeChevron
msoShapeCircularArrow
msoShapeCloudCallout
msoShapeCross
msoShapeCube
msoShapeCurvedDownArrow
msoShapeCurvedDownRibbon
msoShapeCurvedLeftArrow
msoShapeCurvedRightArrow
msoShapeCurvedUpArrow
msoShapeCurvedUpRibbon
msoShapeDiamond
msoShapeDonut
msoShapeDoubleBrace
msoShapeDoubleBracket
msoShapeDoubleWave
msoShapeDownArrow
msoShapeDownArrowCallout
msoShapeDownRibbon
msoShapeExplosion1
msoShapeExplosion2
msoShapeFlowchartAlternateProcess
msoShapeFlowchartCard
msoShapeFlowchartCollate

Left   Required Single. The position, measured in points, of the left edge of the AutoShape.

Top   Required Single. The position, measured in points, of the top edge of the AutoShape.

Width   Required Single. The width, measured in points, of the AutoShape.

Height   Required Single. The height, measured in points, of the AutoShape.

ShowAddShape method as it applies to the Shapes object.

Adds an AutoShape to a document. Returns a Shape object that represents the AutoShape and adds it to the Shapes collection.

expression.AddShape(Type, Left, Top, Width, Height, Anchor)

expression    Required. An expression that returns a Shapes object.

Type   Required Long. The type of shape to be returned. Can be any MsoAutoShapeType
constant.

MsoAutoShapeType can be one of these MsoAutoShapeType constants.
msoShapeFlowchartDirectAccessStorage
msoShapeFlowchartDocument
msoShapeFlowchartInternalStorage
msoShapeFlowchartManualInput
msoShapeFlowchartMerge
msoShapeFlowchartOffpageConnector
msoShapeFlowchartPredefinedProcess
msoShapeFlowchartProcess
msoShapeLeftBracket
msoShapeFlowchartConnector
msoShapeFlowchartData
msoShapeFlowchartDecision
msoShapeFlowchartDelay
msoShapeFlowchartDisplay
msoShapeFlowchartExtract
msoShapeFlowchartMagneticDisk
msoShapeFlowchartManualOperation
msoShapeFlowchartMultidocument
msoShapeFlowchartOr
msoShapeFlowchartPreparation
msoShapeFlowchartPunchedTape
msoShapeFlowchartSequentialAccessStorage
msoShapeFlowchartSort
msoShapeFlowchartStoredData
msoShapeFlowchartSummingJunction
msoShapeFlowchartTerminator
msoShapeFoldedCorner
msoShapeHeart
msoShapeHexagon
msoShapeHorizontalScroll
msoShapeIsoscelesTriangle
msoShapeLeftArrow
msoShapeLeftArrowCallout
msoShapeLeftBrace
msoShapeLeftRightArrow
msoShapeLeftRightArrowCallout
msoShapeLeftRightUpArrow
msoShapeLeftUpArrow
msoShapeLightningBolt
msoShapeLineCallout1
msoShapeLineCallout1AccentBar
msoShapeLineCallout1BorderandAccentBar
msoShapeLineCallout1NoBorder
msoShapeLineCallout2
msoShapeLineCallout2AccentBar
msoShapeLineCallout2BorderandAccentBar
msoShapeLineCallout2NoBorder
msoShapeLineCallout3
msoShapeLineCallout3AccentBar
msoShapeLineCallout3BorderandAccentBar
msoShapeLineCallout3NoBorder
msoShapeLineCallout4
msoShapeLineCallout4AccentBar
msoShapeLineCallout4BorderandAccentBar
msoShapeLineCallout4NoBorder
msoShapeMixed
msoShapeMoon
msoShapeNoSymbol
msoShapeNotchedRightArrow
msoShapeNotPrimitive
msoShapeOctagon
msoShapeOval
msoShapeOvalCallout
msoShapeParallelogram
msoShapePentagon
msoShapePlaque
msoShapeQuadArrow
msoShapeQuadArrowCallout
msoShapeRectangle
msoShapeRectangularCallout
msoShapeRegularPentagon
msoShapeRightArrow
msoShapeRightArrowCallout
msoShapeRightBrace
msoShapeRightBracket
msoShapeRightTriangle
msoShapeRoundedRectangle
msoShapeRoundedRectangularCallout
msoShapeSmileyFace
msoShapeStripedRightArrow
msoShapeSun
msoShapeTrapezoid
msoShapeUpArrow
msoShapeUpArrowCallout
msoShapeUpDownArrow
msoShapeUpDownArrowCallout
msoShapeUpRibbon
msoShapeUTurnArrow
msoShapeVerticalScroll
msoShapeWave
msoShape16pointStar
msoShape24pointStar
msoShape32pointStar
msoShape4pointStar
msoShape5pointStar
msoShape8pointStar
msoShapeActionButtonBackorPrevious
msoShapeActionButtonBeginning
msoShapeActionButtonCustom
msoShapeActionButtonDocument
msoShapeActionButtonEnd
msoShapeActionButtonForwardorNext
msoShapeActionButtonHelp
msoShapeActionButtonHome
msoShapeActionButtonInformation
msoShapeActionButtonMovie
msoShapeActionButtonReturn
msoShapeActionButtonSound
msoShapeArc
msoShapeBalloon
msoShapeBentArrow
msoShapeBentUpArrow
msoShapeBevel
msoShapeBlockArc
msoShapeCan
msoShapeChevron
msoShapeCircularArrow
msoShapeCloudCallout
msoShapeCross
msoShapeCube
msoShapeCurvedDownArrow
msoShapeCurvedDownRibbon
msoShapeCurvedLeftArrow
msoShapeCurvedRightArrow
msoShapeCurvedUpArrow
msoShapeCurvedUpRibbon
msoShapeDiamond
msoShapeDonut
msoShapeDoubleBrace
msoShapeDoubleBracket
msoShapeDoubleWave
msoShapeDownArrow
msoShapeDownArrowCallout
msoShapeDownRibbon
msoShapeExplosion1
msoShapeExplosion2
msoShapeFlowchartAlternateProcess
msoShapeFlowchartCard
msoShapeFlowchartCollate

Left   Required Single. The position, measured in points, of the left edge of the AutoShape.

Top   Required Single. The position, measured in points, of the top edge of the AutoShape.

Width   Required Single. The width, measured in points, of the AutoShape.

Height   Required Single. The height, measured in points, of the AutoShape.

Anchor   Optional Variant. A Range object that represents the text to which the AutoShape is bound. If Anchor is specified, the anchor is positioned at the beginning of the first paragraph in the anchoring range. If this argument is omitted, the anchoring range is selected automatically and the AutoShape is positioned relative to the top and left edges of the page.

Remarks

To change the type of an AutoShape that you’ve added, set the AutoShapeType
property.

Example

ShowAs it applies to the CanvasShapes object.

This example creates a new canvas in the active document and adds a circle to the canvas.

Sub NewCanvasShape()
    Dim shpCanvas As Shape
    Dim shpCanvasShape As Shape

    'Add a new drawing canvas to the active document
    Set shpCanvas = ActiveDocument.Shapes.AddCanvas( _
        Left:=100, Top:=75, Width:=150, Height:=200)

    'Add a circle to the drawing canvas
    Set shpCanvasShape = shpCanvas.CanvasItems.AddShape( _
        Type:=msoShapeOval, Left:=25, Top:=25, _
        Width:=150, Height:=150)
End Sub
				

ShowAs it applies to the Shapes object.

This example adds a red rectangle to a new document.

Sub NewShape()
    Dim docNew As Document

    'Create a new document and adds a shape
    Set docNew = Documents.Add
    docNew.Shapes.AddShape Type:=msoShapeRectangle, _
        Left:=50, Top:=50, Width:=100, Height:=200

    'Format the shape
    docNew.Shapes(1).Fill.ForeColor _
        .RGB = RGB(Red:=200, Green:=15, Blue:=95)
End Sub
				

Shapes: It is a collection which comes under Document object and requires following parameters to be set. The AddShpe method of Shapes collection will let you add shape in the document through code.

Required Parameters:

  • Type: It has MsoAutoShapeType enum which offers many constants to form various inbuilt shapes. Just put the dot and you see list of various available shapes which you can create in your document.
  • Left: Left edge of the shape
  • Top: Top edge of the shape
  • Width: Width of the shape
  • Height: Height of the shape

All parameters (Left, Top, Width, Height) are measured in points. Following code will create two arrows in different directions:

Sub InsertShap()
    ActiveDocument.Shapes.AddShape MsoAutoShapeType.msoShapeLeftArrow, 20, 50, 100, 80
    ActiveDocument.Shapes.AddShape MsoAutoShapeType.msoShapeRightArrow, 160, 50, 100, 80
End Sub

Output:

Доброго времени суток всем читателям и подписчикам блога scriptcoding.ru. В этой статье мы рассмотрим работу с коллекцией Shapes, которая позволяет добавлять различные графические объекты в Word документ.

По сути, используя методы данной коллекции, мы можем делать вставку таких графических объектов в Word как авто-фигуры, выноски, рисунки, диаграммы, полотна и многое другое. Также стоит уточнить, что по ходу статьи, под словом «фигура» будут подразумеваться все графические Word объекты (полотно, WordArt, SmartArtи так далее). Я не привожу примеров программного кода, самим программированием мы займемся, когда будет изучать по отдельности работу с каждым графическим объектом Word, которые создаются с помощью коллекции Shapes.

Содержание

  1. Коллекция Shapes – графические объекты в Word
  2. Shapes – свойства, работа с графическими объектами Word
  3. Shapes — методы, создание графических объектов в Word

Коллекция Shapes – графические объекты в Word

Shapes – свойства, работа с графическими объектами Word

Count— Возвращает количество фигур в коллекции.

Shapes — методы, создание графических объектов в Word

работа с графическими Word объектами

Основной функционал коллекции заключается в ее методах, большинство из которых будут возвращать класс Shape, а тот в свою очередь, будет предоставлять нужные свойства для конкретной фигуры. Например, мы добавили новое полотно в документ, для обработки данного полотна используется свойство CanvasItems, которое хранит ссылку на CanvasShapes. При добавлении новой линии в документ, нам нужно обратиться к свойству Line, которое хранит ссылку на класс LineFormat, который отвечает за обработку линий. И так далее, это логично, так как у каждого графического объекта в Word, например, выноски и WordArt есть различные возможности.

AddCanvas(Left, Top, Width, Height, Anchor) — Добавляет новое полотно в документ.

Anchor – Содержит ссылку на класс Range, который представляет текст, к которому нужно привязать полотно.

AddSmartArt(Layout, Left, Top, Width, Height, Anchor) – Вставка таких графических объектов Word в активный документ, как рисунок SmartArt. Начиная с версии Word 2010.

Layout – Ссылка на класс SmartArtLayout.

AddCallout(Type, Left, Top, Width, Height) – Добавляет текстовую выноску с линиями.

Type – Данный параметр определяет тип линии. Значения константы MsoCalloutType:

  • msoCalloutOne — 1 – Горизонтальная линия слева.
  • msoCalloutTwo — 2 – Горизонтальна линия с наклоном лева.
  • msoCalloutThree — 3 – Линия состоит из двух отрезков слева (один отрезок с наклоном, а другой горизонтальный).
  • msoCalloutFour — 4 — Линия состоит из трех отрезков справа (один отрезок с наклоном, другой горизонтальный и третий вертикальный).

AddLine(BeginX, BeginY, EndX, EndY) – Рисует линию с указанными начальными и конечными координатами.

AddConnector(Type, Left, Top, Width, Height) – Рисует соединительную линию.

Type – Тип линии, значение константы MsoConnectorType:

  • msoConnectorStraight — 1 — Прямая линия.
  • msoConnectorElbow — 2 – Прямое колено.
  • msoConnectorCurve — 3 – Изогнутое колено.
  • msoConnectorTypeMixed — -2 – Смешанные значения.

AddShape(Type, Left, Top, Width, Height) – Вставка графических объектов в Word, которые представляют указанную автофигуру.

Type – Определяет тип фигуры, значение константы MsoAutoShapeType.

AddPicture(FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height) — Добавляет изображения. Возвращает класс Shape, представляющий картинку и добавляет ее в коллекцию CanvasShapes. Обязательный только первый параметр.

FileName – Путь к файлу и его имя.

LinkToFile – True – привязать изображение к файлу, из которого он был создан. False – сделать изображение независимым от файла, по умолчанию.

SaveWithDocument – True — сохранить связанный рисунок с документом. Значение по умолчанию False. Если использовать значение False, то может возникнуть ошибка. Работа с графическими Word объектами.

создание в word графических объектов

AddLabel(Orientation, Left, Top, Width, Height) — Добавляет текстовую область.

Orientation – Задает ориентацию текста. Значение константы MsoTextOrientation:

  • msoTextOrientationHorizontal — 1 — Горизонтальная.
  • msoTextOrientationUpward — 2 – Направление вверх.
  • msoTextOrientationDownward — 3 – Направление вниз.
  • msoTextOrientationVerticalFarEast — 4 – Вертикальное направление для азиатских языков.
  • msoTextOrientationVertical — 5 – Направление вниз.
  • msoTextOrientationHorizontalRotatedFarEast — 6 — Горизонтальное направление для азиатских языков.

AddTextbox(Orientation, Left, Top, Width, Height) — Добавляет текстовое поле.

AddTextEffect(PresetTextEffect, Text, FontName, FontSize, FontBold, FontItalic, Left, Top) – Создание графического объекта WordArt в Word.

PresetTextEffect – Определяет эффект текста WordArt. Значение константы MsoPresetTextEffect.

Text — Текст в WordArt.

FontName — Название шрифта, используемого в WordArt.

FontSize — Размер шрифта в пунктах.

FontBold – Содержит логическое значение, определяющее, нужно ли сделать шрифт жирным (true) или нет (false).

FontItalic — Содержит логическое значение, определяющее, сделать шрифт курсивом (true) или нет (false).

Item(index) — Возвращает отдельный класс Shape в коллекции Shapes по его индексу.

Range(index) — Возвращает ShapeRange, представляющий графические объекты в Word внутри заданного диапазона. Данный метод позволяет выбрать несколько графических Word объектов для будущей их группировки или обработки.

Index — Указывает, какие графические объекты Word должны быть включены в указанный диапазон. Может быть целое число, указывающее порядковый номер фигуры в коллекции Shapes, строка, которая определяет имя фигуры, или массив, содержащий целые числа или строки. Например:

ActiveDocument.Shapes.Range(Array("Oval 5", "Rectangle 4")).Select

SelectAll() — Выбирает все графические объекты в Word в коллекции Shapes. Этот метод не выбирает классы InlineShape. Вы не можете использовать этот метод, чтобы выбрать более одного полотна.

AddPolyline(SafeArrayOfPoints) — Добавляет открытый или закрытый полигон. Возвращает Shape, который представляет многоугольник и добавляет его в коллекцию CanvasShapes.

SafeArrayOfPoints — Массив с парами координат, которые определяют вершины и контрольные точки кривой.

AddCurve(SafeArrayOfPoints) — Возвращает Shape, который представляет кривую Безье.

BuildFreeform(EditingType, X1, Y1) – Создание свободного графического объекта в Word, вернет класс FreeformBuilder. По сути, данный метод позволяет добавить только первый узел будущей фигуры, а уже далее нужно использовать функционал класса FreeformBuilder.

EditingType – Свойства узла. Значение константы MsoEditingType:

  • msoEditingAuto — 0 – Подключение узла.
  • msoEditingCorner — 1 — Угловой узел.
  • msoEditingSmooth — 2 — Гладкий узел.
  • msoEditingSymmetric — 3 — Симметричный узел.

X1 и Y1— Определяют положение узла в пунктах.

AddChart(Style, Type, Left, Top, Width, Height, Anchor, NewLayout) — Добавляет диаграмму в документе.

Style — Стиль диаграммы, целое значение

Type — Тип диаграммы, значение константы XlChartType.

Left – Положение диаграммы в пунктах от левого края.

Top — Положение диаграммы в пунктах от верхнего края.

Width и Height — Ширина и высота в пунктах.

Anchor – Диапазон, который будет связан с графическим объектом в Word.

NewLayout — Если значение true, то график будут вставлен с помощью новых динамические правил форматирования.

AddOLEControl(ClassType, Range) – Добавляет в документ элемент управления ActiveX (ранее известный как элемент управления OLE). Возвращает InlineShape, представляющий новый элемент управления ActiveX. Чтобы изменить свойства элемента управления ActiveX, можно использовать свойство Objectкласса OLEFormat для заданной фигуры.

ClassType — Данный параметр принимает строковое значение, которое содержит имя элемента управления ActiveX. Например:

  • CheckBox — «Forms.CheckBox.1».
  • ComboBox — «Forms.ComboBox.1».
  • CommandButton — «Forms.CommandButton.1».
  • Frame — «Forms.Frame.1».
  • Image — «Forms.Image.1».
  • Label — «Forms.Label.1».
  • ListBox — «Forms.ListBox.1».
  • MultiPage — «Forms.MultiPage.1».
  • OptionButton — «Forms.OptionButton.1».
  • ScrollBar — «Forms.ScrollBar.1».
  • SpinButton — «Forms.SpinButton.1».
  • TabStrip — «Forms.TabStrip.1».
  • TextBox — «Forms.TextBox.1».
  • ToggleButton — «Forms.ToggleButton.1».

Range — Диапазон, в котором нужно разместить элемент управления ActiveX. Если этот аргумент опущен, то ActiveX размещается автоматически.

I want to remove and add an existing Shape in Word (Header and Footer) with a Button

But i can’t select the shape to change the visible property.

How can I do this? I can’t figure out the name of the shape in Word

Thanks for your Help!

Sub LogoChangeVisible()
'
' Removes and adds the logo from Header and Footer
'
'
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

Selection.HeaderFooter.Shapes("Picture from Header").Select

If Selection.ShapeRange.Visible = msoTrue Then
Selection.ShapeRange.Visible = msoFalse
Selection.HeaderFooter.Shapes("Picture from Footer").Select
Selection.ShapeRange.Visible = msoFalse

ElseIf Selection.ShapeRange.Visible = msoFalse Then
Selection.ShapeRange.Visible = msoTrue
Selection.HeaderFooter.Shapes("Picture from Footer").Select
Selection.ShapeRange.Visible = msoTrue
End If

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub

YowE3K's user avatar

YowE3K

23.8k7 gold badges26 silver badges40 bronze badges

asked Jun 19, 2017 at 10:30

c.stinson's user avatar

If you add something like this:

For Each s In Selection.HeaderFooter.Shapes
    Debug.Print s.Name
Next

Then you’ll get the names in your debug window. Another approach is to ignore the names and go by numbers instead:

Selection.HeaderFooter.Shapes(1)...

answered Jun 19, 2017 at 12:21

Sam's user avatar

SamSam

5,1921 gold badge18 silver badges32 bronze badges

2

How to create autoshapes, lines and connectors in VBA macros

Part two of an eight-part series of blogs

You can use Visual Basic within Excel, PowerPoint or Word to draw shapes, format them and even assign macros to run — this long blog gives lots of ideas of how to proceed!

  1. Working with shapes in VBA
  2. Working with shapes — getting started (this blog)
  3. Naming, referring to and positioning shapes
  4. Formatting shapes and adding text
  5. Adding lines and connectors to join shapes together
  6. Working with multiple shapes
  7. Assigning macros to shapes
  8. Exercises on shapes

This is one small part of our free online Excel VBA tutorial.  To find out how to learn in a more structured way, have a look at our training courses in VBA.

Posted by
Andy Brown
on 25 January 2014

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Any worksheet contains a collection of shapes, so often a good place to start
is by deleting any shapes that you’ve already added to a worksheet so that you
can start with a blank canvas.

Looping over shapes

The following macro would delete any shapes which have been added to a
worksheet:

Sub DeleteShapesOnSheet()

Dim w As Worksheet

Dim s As Shape

Set w = ActiveSheet

For Each s In w.Shapes

s.Delete

Next s

End Sub

The macro works by looking at each of the shapes on the worksheet in turn,
applying the Delete method to remove it.

Adding new shapes

The easiest way to add a shape in VBA is to apply the AddShape
method to the existing collection of shapes:

Adding a shape in VBA

Some of the arguments to the
AddShape method (the full list is shown below).

The full list of arguments that you need to specify when adding a shape like
this are as follows:

No. Argument Type Notes
1 Type Integer or enumeration The shape that you’re adding (see below for more on this).
2 Left Single The position of the shape from the left edge of the
worksheet.
3 Top Single The position of the shape from the top edge of the
worksheet.
4 Width Single The width of the shape.
5 Height Single The height of the shape.

All units are in points, which is the typical unit for font size.  When
you read a book or magazine article, the font size is probably between 10
and 14 points high.

You can add a shape either by specifying its enumeration or by using the
integer equivalent.  So both of these commands will add the same rectangle:

Dim w As Worksheet

Set w = ActiveSheet

w.Shapes.AddShape msoShapeRectangle, 10, 10, 30, 20

w.Shapes.AddShape 1, 50, 10, 30, 20

Here are the shapes added by this code:

Two rectangles side by side

The only difference is that one shape is added 10 points in from the left-hand side, and one is added 50 points in from the left.

Whether you choose to specify the shape type by its number or by its enumeration
is up to you!

Listing out the types of shapes

A list of the first 137 autoshape types is shown below (for versions of Excel
up to 2003, that’s all that there is available):

First 137 autoshapes

The main autoshapes in VBA!

Generating the list of shapes

It’s neither particularly well-written or well-commented, but for the sake of
completion (and in case anyone finds it useful for reference), here’s the code I
wrote to generate the above list:

Sub ListShapes()

Dim ws As Worksheet

Dim s As Shape

Dim c As Range

Dim l As Single

Dim t As Single

Dim w As Single

Dim h As Single

Set ws = ActiveSheet

For Each s In ws.Shapes

s.Delete

Next s

Cells.Clear

Dim col As Integer

Dim topcell As Range

For col = 1 To 5

Set topcell = Cells(1, 3 * col — 2)

topcell.Value = «No.»

topcell.Offset(0, 1).Value = «Shape»

topcell.EntireColumn.ColumnWidth = 5

topcell.Offset(0, 1).ColumnWidth = 9

topcell.Offset(0, 2).ColumnWidth = 2

Next col

With Range(«A1:N1»)

.Font.Bold = True

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.Interior.Color = RGB(220, 220, 220)

End With

Dim rowNumber As Integer

Dim colNumber As Integer

Dim shapeNumber As Integer

colNumber = 1

rowNumber = 1

For shapeNumber = 1 To 137

rowNumber = rowNumber + 1

If rowNumber > 29 Then

rowNumber = 2

colNumber = colNumber + 3

End If

Set c = Cells(rowNumber, colNumber)

c.Value = shapeNumber

l = c.Offset(0, 1).Left + 10

t = c.Offset(0, 1).Top + 5

w = 35

h = 12

Set s = ws.Shapes.AddShape(shapeNumber, l, t, w, h)

c.HorizontalAlignment = xlCenter

c.VerticalAlignment = xlCenter

c.RowHeight = 20

If colNumber < 13 Then

c.Offset(0, 2).Interior.Color = RGB(220, 220, 220)

End If

Next shapeNumber

MsgBox «Done!»

End Sub

If you’re new to shapes, you’ll need to read on in this blog to learn more
about how they work to understand the above code!

Having learnt the basics of adding shapes, let’s now look at how to name and
position them.

This blog has 0 threads

Add post

Понравилась статья? Поделить с друзьями:
  • Vba add row excel vba
  • Vba excel 2010 таблица
  • Vba add button excel
  • Vba excel 2010 скачать бесплатно
  • Vba access таблица word