Vba excel shapes group

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Working with shapes (drawing objects)

vbaxl10.chm5206010

vbaxl10.chm5206010

excel

aef5dc81-d54f-a01a-f949-a30688a3cf23

11/13/2018

medium

Shapes, or drawing objects, are represented by three different objects:

Object Description
Shapes collection Use to create shapes and to iterate through all the shapes on a given worksheet.
ShapeRange collection Use to modify multiple shapes the same way you work with multiple shapes in the user interface.
Shape object Use to format or modify a single shape.

Setting properties for a shape

Many formatting properties of shapes are not set by properties that apply directly to the Shape or ShapeRange object. Instead, related shape attributes are grouped under secondary objects, such as the FillFormat object, which contains all the properties that relate to the shape’s fill, or the LinkFormat object, which contains all the properties that are unique to linked OLE objects.

To set properties for a shape, you must first return the object that represents the set of related shape attributes and then set properties of that returned object. For example, you use the Fill property to return the FillFormat object, and then you set the ForeColor property of the FillFormat object to set the fill foreground color for the specified shape, as shown in the following example.

Worksheets(1).Shapes(1).Fill.ForeColor.RGB = RGB(255, 0, 0)

Applying a property or method to several shapes at the same time

In the user interface, you can perform some operations with several shapes selected; for example, you can select several shapes and set all their individual fills at once. You can perform other operations with only a single shape selected; for example, you can edit the text in a shape only if a single shape is selected.

In Visual Basic, there are two ways to apply properties and methods to a set of shapes. These two ways allow you to perform any operation that you can perform on a single shape on a range of shapes, whether or not you can perform the same operation in the user interface.

  • If the operation works on multiple selected shapes in the user interface, you can perform the same operation in Visual Basic by constructing a ShapeRange collection that contains the shapes you want to work with, and applying the appropriate properties and methods directly to the ShapeRange collection.

  • If the operation does not work on multiple selected shapes in the user interface, you can still perform the operation in Visual Basic by looping through the Shapes collection or through a ShapeRange collection that contains the shapes you want to work with, and applying the appropriate properties and methods to the individual Shape objects in the collection.

Many properties and methods that apply to the Shape object and ShapeRange collection fail if applied to certain kinds of shapes. For example, the TextFrame property fails if applied to a shape that cannot contain text.

If you are not positive that each of the shapes in a ShapeRange collection can have a certain property or method applied to it, don’t apply the property or method to the ShapeRange collection. If you want to apply one of these properties or methods to a collection of shapes, you must loop through the collection and test each individual shape to make sure it is an appropriate type of shape before applying the property or method to it.

Creating a ShapeRange collection that contains all shapes on a sheet

You can create a ShapeRange object that contains all the Shape objects on a sheet by selecting the shapes and then using the ShapeRange property to return a ShapeRange object containing the selected shapes.

Worksheets(1).Shapes.Select 
Set sr = Selection.ShapeRange

In Microsoft Excel, the Index argument is not optional for the Range property of the Shapes collection, so you cannot use this property without an argument to create a ShapeRange object containing all shapes in a Shapes collection.

Applying a property or method to a ShapeRange collection

If you can perform an operation on multiple selected shapes in the user interface at the same time, you can do the programmatic equivalent by constructing a ShapeRange collection and then applying the appropriate properties or methods to it. The following example constructs a shape range that contains the shapes named «Big Star» and «Little Star» on myDocument and applies a gradient fill to them.

Set myDocument = Worksheets(1) 
Set myRange = myDocument.Shapes.Range(Array("Big Star", _ 
 "Little Star")) 
myRange.Fill.PresetGradient _ 
 msoGradientHorizontal, 1, msoGradientBrass

The following are general guidelines for how properties and methods behave when they are applied to a ShapeRange collection.

  • Applying a method to the collection is equivalent to applying the method to each individual Shape object in that collection.

  • Setting the value of a property of the collection is equivalent to setting the value of the property of each individual shape in that range.

  • A property of the collection that returns a constant returns the value of the property for an individual shape in the collection if all shapes in the collection have the same value for that property. If not all shapes in the collection have the same value for the property, it returns the «mixed» constant.

  • A property of the collection that returns a simple data type (such as Long, Single, or String) returns the value of the property for an individual shape if all shapes in the collection have the same value for that property.

  • The value of some properties can be returned or set only if there is exactly one shape in the collection. If the collection contains more than one shape, a run-time error occurs. This is generally the case for returning or setting properties when the equivalent action in the user interface is possible only with a single shape (actions such as editing text in a shape or editing the points of a freeform).

The preceding guidelines also apply when you are setting properties of shapes that are grouped under secondary objects of the ShapeRange collection, such as the FillFormat object. If the secondary object represents operations that can be performed on multiple selected objects in the user interface, you’ll be able to return the object from a ShapeRange collection and set its properties.

For example, you can use the Fill property to return the FillFormat object that represents the fills of all the shapes in the ShapeRange collection. Setting the properties of this FillFormat object will set the same properties for all the individual shapes in the ShapeRange collection.

Looping through a Shapes or ShapeRange collection

Even if you cannot perform an operation on several shapes in the user interface at the same time by selecting them and then using a command, you can perform the equivalent action programmatically by looping through a Shapes or ShapeRange collection that contains the shapes you want to work with, applying the appropriate properties and methods to the individual Shape objects in the collection.

The following example loops through all the shapes on myDocument and changes the foreground color for each AutoShape shape.

Set myDocument = Worksheets(1) 
For Each sh In myDocument.Shapes 
 If sh.Type = msoAutoShape Then 
 sh.Fill.ForeColor.RGB = RGB(255, 0, 0) 
 End If 
Next

The following example constructs a ShapeRange collection that contains all the currently selected shapes in the active window and sets the foreground color for each selected shape.

For Each sh in ActiveWindow.Selection.ShapeRange 
 sh.Fill.ForeColor.RGB = RGB(255, 0, 0) 
Next

Aligning, distributing, and grouping shapes in a ShapeRange

Use the Align and Distribute methods to position a set of shapes relative to one another or relative to the document that contains them.

Use the Group method or the Regroup method to form a single grouped shape from a set of shapes.

See also

  • Excel functions (by category)

[!includeSupport and feedback]

Содержание

  1. Свойство GroupShapes.Range (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Working with shapes (drawing objects)
  8. Setting properties for a shape
  9. Applying a property or method to several shapes at the same time
  10. Creating a ShapeRange collection that contains all shapes on a sheet
  11. Applying a property or method to a ShapeRange collection
  12. Looping through a Shapes or ShapeRange collection
  13. Aligning, distributing, and grouping shapes in a ShapeRange
  14. See also
  15. Support and feedback
  16. VBA Vault
  17. Group All Shapes Within A Selection Of Cells
  18. What This VBA Code Does
  19. VBA Code:
  20. Using VBA Code Found On The Internet
  21. Getting Started Automating Excel
  22. How Do I Modify This To Fit My Specific Needs?

Свойство GroupShapes.Range (Excel)

Возвращает объект ShapeRange , представляющий подмножество фигур в коллекции Shapes .

Синтаксис

expression. Диапазон (индекс)

Выражение Переменная, представляющая объект GroupShapes .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Индекс; Обязательный Variant Отдельные фигуры, которые будут включены в диапазон. Может быть целым числом, указывающим номер индекса фигуры, строкой, указывающей имя фигуры, или массивом, содержащим либо целые числа, либо строки.

Замечания

Хотя свойство Range можно использовать для возврата любого количества фигур, проще использовать метод Item , если требуется вернуть только один член коллекции. Например, проще, Shapes(1) чем Shapes.Range(1) .

Пример

В этом примере задается шаблон заливки для фигур один и три в myDocument.

Чтобы указать массив целых чисел или строк для index, можно использовать функцию Array . Например, следующая инструкция возвращает две фигуры, указанные по имени.

В Microsoft Excel это свойство нельзя использовать для возврата объекта ShapeRange , содержащего все объекты Shape на листе. Вместо этого используйте следующий код.

В этом примере задается шаблон заливки для фигур с именами Oval 4 и Rectangle 5 в myDocument.

В этом примере задается шаблон заливки для фигуры в myDocument.

В этом примере создается массив, который содержит все автофигуры в myDocument, использует этот массив для определения диапазона фигур, а затем распределяет все фигуры в этом диапазоне по горизонтали.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Working with shapes (drawing objects)

Shapes, or drawing objects, are represented by three different objects:

Object Description
Shapes collection Use to create shapes and to iterate through all the shapes on a given worksheet.
ShapeRange collection Use to modify multiple shapes the same way you work with multiple shapes in the user interface.
Shape object Use to format or modify a single shape.

Setting properties for a shape

Many formatting properties of shapes are not set by properties that apply directly to the Shape or ShapeRange object. Instead, related shape attributes are grouped under secondary objects, such as the FillFormat object, which contains all the properties that relate to the shape’s fill, or the LinkFormat object, which contains all the properties that are unique to linked OLE objects.

To set properties for a shape, you must first return the object that represents the set of related shape attributes and then set properties of that returned object. For example, you use the Fill property to return the FillFormat object, and then you set the ForeColor property of the FillFormat object to set the fill foreground color for the specified shape, as shown in the following example.

Applying a property or method to several shapes at the same time

In the user interface, you can perform some operations with several shapes selected; for example, you can select several shapes and set all their individual fills at once. You can perform other operations with only a single shape selected; for example, you can edit the text in a shape only if a single shape is selected.

In Visual Basic, there are two ways to apply properties and methods to a set of shapes. These two ways allow you to perform any operation that you can perform on a single shape on a range of shapes, whether or not you can perform the same operation in the user interface.

If the operation works on multiple selected shapes in the user interface, you can perform the same operation in Visual Basic by constructing a ShapeRange collection that contains the shapes you want to work with, and applying the appropriate properties and methods directly to the ShapeRange collection.

If the operation does not work on multiple selected shapes in the user interface, you can still perform the operation in Visual Basic by looping through the Shapes collection or through a ShapeRange collection that contains the shapes you want to work with, and applying the appropriate properties and methods to the individual Shape objects in the collection.

Many properties and methods that apply to the Shape object and ShapeRange collection fail if applied to certain kinds of shapes. For example, the TextFrame property fails if applied to a shape that cannot contain text.

If you are not positive that each of the shapes in a ShapeRange collection can have a certain property or method applied to it, don’t apply the property or method to the ShapeRange collection. If you want to apply one of these properties or methods to a collection of shapes, you must loop through the collection and test each individual shape to make sure it is an appropriate type of shape before applying the property or method to it.

Creating a ShapeRange collection that contains all shapes on a sheet

You can create a ShapeRange object that contains all the Shape objects on a sheet by selecting the shapes and then using the ShapeRange property to return a ShapeRange object containing the selected shapes.

In Microsoft Excel, the Index argument is not optional for the Range property of the Shapes collection, so you cannot use this property without an argument to create a ShapeRange object containing all shapes in a Shapes collection.

Applying a property or method to a ShapeRange collection

If you can perform an operation on multiple selected shapes in the user interface at the same time, you can do the programmatic equivalent by constructing a ShapeRange collection and then applying the appropriate properties or methods to it. The following example constructs a shape range that contains the shapes named «Big Star» and «Little Star» on myDocument and applies a gradient fill to them.

The following are general guidelines for how properties and methods behave when they are applied to a ShapeRange collection.

Applying a method to the collection is equivalent to applying the method to each individual Shape object in that collection.

Setting the value of a property of the collection is equivalent to setting the value of the property of each individual shape in that range.

A property of the collection that returns a constant returns the value of the property for an individual shape in the collection if all shapes in the collection have the same value for that property. If not all shapes in the collection have the same value for the property, it returns the «mixed» constant.

A property of the collection that returns a simple data type (such as Long, Single, or String) returns the value of the property for an individual shape if all shapes in the collection have the same value for that property.

The value of some properties can be returned or set only if there is exactly one shape in the collection. If the collection contains more than one shape, a run-time error occurs. This is generally the case for returning or setting properties when the equivalent action in the user interface is possible only with a single shape (actions such as editing text in a shape or editing the points of a freeform).

The preceding guidelines also apply when you are setting properties of shapes that are grouped under secondary objects of the ShapeRange collection, such as the FillFormat object. If the secondary object represents operations that can be performed on multiple selected objects in the user interface, you’ll be able to return the object from a ShapeRange collection and set its properties.

For example, you can use the Fill property to return the FillFormat object that represents the fills of all the shapes in the ShapeRange collection. Setting the properties of this FillFormat object will set the same properties for all the individual shapes in the ShapeRange collection.

Looping through a Shapes or ShapeRange collection

Even if you cannot perform an operation on several shapes in the user interface at the same time by selecting them and then using a command, you can perform the equivalent action programmatically by looping through a Shapes or ShapeRange collection that contains the shapes you want to work with, applying the appropriate properties and methods to the individual Shape objects in the collection.

The following example loops through all the shapes on myDocument and changes the foreground color for each AutoShape shape.

The following example constructs a ShapeRange collection that contains all the currently selected shapes in the active window and sets the foreground color for each selected shape.

Aligning, distributing, and grouping shapes in a ShapeRange

Use the Align and Distribute methods to position a set of shapes relative to one another or relative to the document that contains them.

Use the Group method or the Regroup method to form a single grouped shape from a set of shapes.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Vault

An Excel, PowerPoint, & MS Word blog providing handy and creative VBA code snippets. These macro codes are well commented and are completely functional when copied into a module.

Group All Shapes Within A Selection Of Cells

What This VBA Code Does

This VBA code is a nifty little I created to solve the hassle of selecting each shape individually in order to group them. With this code, you can essentially select a range of cells and any shapes within that selected range will get automatically grouped together. Once you have this capability added to your personal macro workbook, you won’t know how you ever lived without it! Enjoy!!

VBA Code:

Sub GroupShapesInsideCellRange()
‘PURPOSE: Group all Shapes within a User’s Selected Range
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim shp As Shape
Dim rng As Range
Dim grp As Object

‘Pull-in what is selected on screen
Set UserSelection = ActiveWindow.Selection

‘Test to see if there is a range selected by the user
On Error Resume Next
Set rng = Selection
On Error GoTo 0

‘Group Shapes Within Selected Range
If Not rng Is Nothing Then

‘Hide any Shape Outside of User’s Selected Range
For Each shp In ActiveSheet.Shapes
If Intersect(rng, shp.TopLeftCell) Is Nothing And _
Intersect(rng, shp.BottomRightCell) Is Nothing Then
If shp.Type <> msoComment Then shp.Visible = msoFalse
End If
Next shp

‘Select All Visible Shapes
On Error GoTo Skip
ActiveSheet.Shapes.SelectAll
On Error GoTo 0

‘Group Shapes Together and select
If VarType(Selection) = 9 Then
Set grp = Selection.Group
grp.Select
End If

Skip:
‘Unhide the rest of the Shapes
For Each shp In ActiveSheet.Shapes
If shp.Type <> msoComment Then
If shp.Visible = msoFalse Then shp.Visible = msoTrue
End If
Next shp
End If

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Источник

  • #2

I suggest you record a macro.

Once shapes are grouped we cannot change them individually.

You may just need to change the size of the Group.
(select the group and look at name box top left of sheet)

  • #3

Thank-you for getting back!
This I’ve discovered through trial and error.
Any tier of Grouped Shapes CAN be accessed through VBA (2007).

If the Work Sheet contains 2 or more Groups or Shapes with the same name, the code below will access the Group or shape at the bottom on the Selection and Visibility pane only (in this case «Outside Diameter»).

Sub Shapes()
ActiveSheet.Shapes(«Outside Diameter»).LockAspectRatio = msoFalse
ActiveSheet.Shapes(«Outside Diameter»).Height = 40
ActiveSheet.Shapes(«Outside Diameter»).Width = 40
ActiveSheet.Shapes(«Outside Diameter»).LockAspectRatio = msoTrue
End Sub

So at this point I’m looking for a way to get the Code to move through all the Groups or Shapes that match it’s criteria.

Ian

  • #5

That occurred to me — that I should give each Shape a unique name.

I am having the same problem as crackjack in that when I record Macros, there’s nothing Recorded.

Ian

  • #6

2010 does record Drawing Tools based Macros, so that’s helpful.

Ian

  • #7

I can get this code to work for one Shape, but not multiple.

Not have time to do code. If you set a variable to include all shapes in a ShapeRange (search on this) you can change the whole lot in one go.

  • #8

Thank-you Brian.
I’m also thinking the AutoShapes may be more solid with 2010, in that they don’t change size on their own (which was the case with 2007).

Ian

  • #9

may be more solid with 2010,

Works fine in XL2000 :LOL:

ZVI

ZVI

MrExcel MVP


  • #10

Hi Ian,

1) I would suggest to install all service packs for Excel 2007.

2) All shapes even items of the grouped one are accessible via VBA:

Rich (BB code):


Sub Test()
  Dim Shp1 As Shape, Shp2 As Shape
  On Error Resume Next
  For Each Shp1 In ActiveSheet.Shapes
    Debug.Print Shp1.Name, Shp1.Width, Shp1.Height
    For Each Shp2 In Shp1.GroupItems
      Debug.Print vbTab & Shp2.Name, Shp2.Width, Shp2.Height
'      If Shp2.Name = "MyShapeName" Then
'        Shp2.Width = 36
'        Shp2.Height = 258
'      End If
    Next
  Next
End Sub

Regards,
Vladimir

 

guzen_pilot

Пользователь

Сообщений: 62
Регистрация: 28.02.2016

#1

23.04.2016 18:19:37

Уважаемые форумчане, подскажите как грамотно реализовать нечто подобное:

Код
With Worksheets("Лист1").Shapes.группа(1)
    .AddLine 1,2,3,4
    .AddLine 5,6,7,8
End With
With Worksheets("Лист1").Shapes.группа(2)
    .AddLine 1,2,3,4
    .AddLine 5,6,7,8
End With
Worksheets("Лист1").Shapes.группа(1).Line.Weight = 3

то есть создавать однотипные объекты в разных группах, а потом работать отдельно с каждой группой
головой понимаю, что можно, но найти не смог

Помогли? отпишись, а то мы же волнуемся )))

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#2

23.04.2016 18:57:30

такой вариант:

Код
Sub jjj()
        
    Dim ws As Worksheet, arrGroup1() As Shape, arrGroup2() As Shape
    Dim i As Long
    
    Set ws = ActiveSheet
    
    ReDim arrGroup1(1 To 1)
    Set arrGroup1(UBound(arrGroup1)) = ws.Shapes.AddLine(1, 2, 3, 4)
    ReDim Preserve arrGroup1(1 To UBound(arrGroup1) + 1)
    Set arrGroup1(UBound(arrGroup1)) = ws.Shapes.AddLine(5, 6, 7, 8)
   
    ReDim arrGroup2(1 To 1)
    Set arrGroup2(UBound(arrGroup2)) = ws.Shapes.AddLine(1, 2, 3, 4)
    ReDim Preserve arrGroup2(1 To UBound(arrGroup2) + 1)
    Set arrGroup2(UBound(arrGroup2)) = ws.Shapes.AddLine(5, 6, 7, 8)
    
    For i = 1 To UBound(arrGroup1)
        arrGroup1(i).Line.Weight = 3
    Next
    
    For i = 1 To UBound(arrGroup2)
        arrGroup2(i).Line.Weight = 3
    Next

End Sub
 

спасибо, что ответили, но не то, я через массивы имен делаю, а это те же яйца…….
по сути нужно одно свойство, общее для группы как Type, но чтобы одни линии отличать от других. Это как подкласс на базе класса. И еще его свойство Range и ShapeRange меня смущает

Изменено: guzen_pilot23.04.2016 22:33:17

Помогли? отпишись, а то мы же волнуемся )))

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#4

23.04.2016 22:40:55

Как добавлять шейпы в уже имеющийся ShapeRange не знаю.
Но вот еще такой вариант:

Код
Sub jjj()
        
    Dim ws As Worksheet, objShapeRange As ShapeRange
    Dim lngCount As Long
    
    Set ws = ActiveSheet
    
    ws.Shapes.AddLine 1, 2, 3, 4
    ws.Shapes.AddLine 5, 6, 7, 8
    lngCount = ws.Shapes.Count
    Set objShapeRange = ws.Shapes.Range(Array(lngCount - 1, lngCount))
    
    objShapeRange.Line.Weight = 3
    
End Sub

Изменено: Karataev23.04.2016 23:33:39

 

guzen_pilot

Пользователь

Сообщений: 62
Регистрация: 28.02.2016

#5

23.04.2016 23:45:18

я по цвету разделил

Код
For Each s_lin In Worksheets("Лист1").Shapes
    If s_lin.Line.ForeColor.RGB <> RGB(200, 200, 200) Then s_lin.Line.Weight = 3
Next

для одних ргб = 200….. , для других 205……. глазу не отличимо, но все равно как-то неспокойно на душе. да и вообще основная идея —  присваивать «некую уникальность» уже в процессе создания фигуры, без With и Select

Изменено: guzen_pilot23.04.2016 23:45:30

Помогли? отпишись, а то мы же волнуемся )))

Работа с фигурами в VBA Excel: создание фигур методом Shapes.AddShape, типы фигур (MsoAutoShapeType), обращение к фигурам и изменение их свойств. Примеры.

Объекты для работы с фигурами

Фигуры в VBA Excel представлены тремя объектами:

Объект Описание
Shapes Коллекция всех фигур на рабочем листе. Используется для создания новых фигур, для обращения к одной фигуре по имени и для перебора фигур циклом.
ShapeRange Коллекция нескольких фигур, аргументом которой является массив имен выбранных объектов. Используется для редактирования сразу всех фигур, входящих в эту коллекцию.
Shape Объект, представляющий одну фигуру. Используется для редактирования одной этой фигуры.

Фигуры в VBA Excel создаются методом Shapes.AddShape.

Синтаксис метода AddShape

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

Shapes — выражение, возвращающее коллекцию фигур на рабочем листе, например: ActiveSheet.Shapes.

Параметры метода AddShape

Параметр Описание
Type Константа из коллекции MsoAutoShapeType, определяющая тип создаваемой фигуры.
Left Расстояние от левой границы фигуры до левой границы табличной части рабочего листа в пунктах.. Тип данных — Single.
Top Расстояние от верхней границы фигуры до верхней границы табличной части рабочего листа в пунктах.. Тип данных — Single.
Width Ширина фигуры по внешним границам в пунктах.
Height Высота фигуры по внешним границам в пунктах.

Все параметры метода Shapes.AddShape являются обязательными.

Константы MsoAutoShapeType

Константы коллекции MsoAutoShapeType, определяющие основные типы создаваемых фигур:

Константа Значение Тип фигуры
msoShapeRectangle 1 Прямоугольник
msoShapeParallelogram 2 Параллелограмм
msoShapeTrapezoid 3 Трапеция
msoShapeDiamond 4 Ромб
msoShapeRoundedRectangle 5 Прямоугольник: скругленные углы
msoShapeOctagon 6 Восьмиугольник (октаэдр)
msoShapeIsoscelesTriangle 7 Равнобедренный треугольник
msoShapeRightTriangle 8 Прямоугольный треугольник
msoShapeOval 9 Овал
msoShapeHexagon 10 Шестиугольник (гексаэдр)
msoShapeCross 11 Крест
msoShapeRegularPentagon 12 Пятиугольник (пентаэдр)
msoShapeCan 13 Цилиндр
msoShapeCube 14 Куб
msoShapeDonut 18 Круг: прозрачная заливка (кольцо)
msoShapeLightningBolt 22 Молния
msoShapeSun 23 Солнце
msoShapeMoon 24 Месяц (луна)
msoShape5pointStar 92 Звезда: 5 точек (пятиконечная)
msoShapeCloud 179 Облако

Все доступные константы из коллекции MsoAutoShapeType смотрите на сайте разработчиков.

Создание объекта ShapeRange

Создание коллекции ShapeRange из выбранных фигур:

Dim myShapeRange As ShapeRange

Set myShapeRange = ActiveSheet.Shapes.Range(Array(«Пятиугольник 140», «Солнце 141», «Облако 144»))

Объектная переменная myShapeRange не обязательна, можно обратиться непосредственно к возвращенной коллекции, например, присвоив всем ее элементам синий цвет:

ActiveSheet.Shapes.Range(Array(«Пятиугольник 140», «Солнце 141», «Облако 144»)).Fill.ForeColor.RGB = vbBlue

Примеры работы с фигурами

Пример 1

Создание пяти разных фигур из кода VBA Excel методом Shapes.AddShape:

Sub Primer1()

    With ActiveSheet.Shapes

        ‘При создании фигуры без присвоения ее переменной скобки не нужны

        .AddShape msoShapeCube, 30, 40, 72, 72

        .AddShape msoShapeIsoscelesTriangle, 130, 40, 72, 72

        .AddShape msoShapeSun, 230, 40, 72, 72

        .AddShape msoShapeLightningBolt, 330, 40, 72, 72

        ‘Чтобы выбрать фигуру, параметры необходимо заключить в скобки

        .AddShape(msoShapeCloud, 430, 40, 72, 72).Select

    End With

End Sub

Результат работы кода:

Фигуры на листе Excel

Пример 2

Работа с одной фигурой:

Sub Primer2()

Dim myShape As Shape

‘Создаем фигуру «Месяц» и присваивает ссылку на нее переменной myShape

Set myShape = ActiveSheet.Shapes.AddShape(msoShapeMoon, 50, 50, 80, 80)

    With myShape

        ‘Меняем высоту и ширину фигуры

        .Height = 150

        .Width = 100

        ‘Меняем цвет фигуры

        .Fill.ForeColor.RGB = vbYellow

        ‘Поворачиваем фигуру влево на 40 градусов

        .Rotation = 40

    End With

End Sub

Пример 3

Редактирование одновременно нескольких фигур с помощью коллекции ShapeRange:

Sub Primer3()

    With ActiveSheet.Shapes.Range(Array(«Овал 1», «Овал 2», «Овал 3»))

        ‘Меняем цвет всех фигур из коллекции ShapeRange

        .Fill.ForeColor.RGB = vbBlue

        ‘Задаем высоту и ширину овалов

        .Height = 150

        .Width = 50

        ‘Поворачиваем фигуры вправо на 45 градусов

        .Rotation = 45

    End With

End Sub

Пример 4

Редактирование одновременно всех фигур на рабочем листе с помощью коллекции ShapeRange:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Sub Primer4()

Dim myShapeRange As ShapeRange, i As Integer, _

myShape As Shape, myArray() As String

‘Задаем массиву размерность от 1 до количества фигур на листе

ReDim myArray(1 To ActiveSheet.Shapes.Count)

    ‘Проходим циклом по всем фигурам коллекции и записываем их имена в массив

    For Each myShape In ActiveSheet.Shapes

        i = i + 1

        myArray(i) = myShape.Name

    Next

‘Создаем коллекцию ShapeRange и присваиваем ссылку на нее переменной myShapeRange

Set myShapeRange = ActiveSheet.Shapes.Range(myArray)

    With myShapeRange

        ‘Изменяем цвет всех фигур на рабочем листе

        .Fill.ForeColor.RGB = RGB(100, 150, 200)

        ‘Поворачиваем все фигуры вокруг вертикальной оси

        .Flip msoFlipVertical

    End With

End Sub

Пример 5

Добавление надписи (текста) на фигуру:

Sub Primer5()

Dim myShape As Shape

Set myShape = ActiveSheet.Shapes.AddShape(msoShapeCloud, 50, 30, 300, 300)

    With myShape.TextFrame2

        ‘Добавление текста на фигуру

        .TextRange.Characters.Text = «Объект TextFrame представляет текстовую рамку в объекте Shape. Содержит текст в текстовом кадре, а также свойства и методы, которые контролируют выравнивание и закрепление текстового кадра.»

        ‘Задаем курсивное начертание

        .TextRange.Characters.Font.Italic = True

        ‘Указываем размер шрифта

        .TextRange.Characters.Font.Size = 13

        ‘Отступ левой границы текстового поля от левой внутренней границы фигуры

        .MarginLeft = 30

        ‘Отступ верхней границы текстового поля от верхней внутренней границы фигуры

        .MarginTop = 20

    End With

End Sub

Результат работы кода:

Фигура Облако с надписью

Изменить цвет текста, например на черный, можно двумя способами:

‘С помощью константы MsoThemeColorIndex

myShape.TextFrame2.TextRange.Characters.Font.Fill.ForeColor.ObjectThemeColor = msoThemeColorDark1

‘С помощью цветовой модели RGB

myShape.TextFrame2.TextRange.Characters.Font.Fill.ForeColor.RGB = RGB(0, 0, 0)

С константами из коллекции MsoThemeColorIndex вы можете ознакомиться на сайте разработчиков.

Пример 6

Удаление фигур с рабочего листа из кода VBA Excel с помощью метода Delete.

Удаление одной фигуры:

ActiveSheet.Shapes(«Ромб 5»).Delete

Удаление нескольких фигур:

ActiveSheet.Shapes.Range(Array(«Овал 1», «Овал 2», «Овал 3»)).Delete

Удаление всех фигур с рабочего листа с помощью цикла:

Sub Primer6()

Dim myShape As Shape

    For Each myShape In ActiveSheet.Shapes

        myShape.Delete

    Next

End Sub

В 7 примере рассмотрено удаление всех фигур без цикла.

Пример 7

Выделение всех фигур на рабочем листе:

ActiveSheet.Shapes.SelectAll

Выбор всех фигур и удаление выбранного (всех фигур):

Sub Primer7()

    ActiveSheet.Shapes.SelectAll

    Selection.Delete

End Sub


Продолжение темы в статье VBA Excel. Копирование, перемещение и поворот фигур.


#excel #vba #shapes

Вопрос:

У меня возникли проблемы с группировкой фигур по имени с помощью VBA в Excel.
Это происходит потому, что у меня есть несколько фигур, которые могут иметь одно и то же имя.

Следующий код может воссоздать мою проблему.
Вы можете раскомментировать строку OriginalShape.Name = "MyShape" , чтобы увидеть ошибку.

 Sub test()
    
    ' Create Original Shape
    Dim OriginalShape As Shape
    Set OriginalShape = Sheet1.Shapes.AddShape(msoShapeRectangle, 5, 20, 50, 50)
    
    ' Rename Shape to simulate my project
'    OriginalShape.Name = "MyShape" ' Uncomment line to recreate problem
    
    ' Copy and Paste Shape (I believe there is no other way to do this)
    OriginalShape.Copy
    Sheet1.Paste Sheet1.Range("C2")
    
    ' Get Object of Last Pasted Shape
    Dim CloneShape As Shape
    Set CloneShape = Sheet1.Shapes(Sheet1.Shapes.Count)
    
    ' Group Shapes
    Dim ShapeGroup As Shape
    Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape.Name, CloneShape.Name)).Group

End Sub
 

Я знаю, что у меня также есть возможность использовать индексы фигур , например Sheet1.Shapes.Range(Array(1, 2)).Group , но это тоже не кажется хорошим способом, так как мне нужно было бы хранить еще одну переменную для каждой фигуры (индекс фигуры) отдельно от объекта фигуры.

Есть ли способ группировать фигуры каким-либо другим способом, например, с помощью объекта или идентификатора. Я считаю, что лучшим было бы что-то вроде.

 Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape, CloneShape)).Group
'OR
Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape.ID, CloneShape.ID)).Group
 

Комментарии:

1. Если фигуры имеют одно и то же имя, как ваш код узнает, какие из них необходимо сгруппировать? Или вы просто хотите сгруппировать все фигуры на листе, или ? Ваш тестовый код мало что говорит нам о том, что вам на самом деле нужно сделать…

Ответ №1:

Как сказал Тим Уильямс: код не работает, так как массив групп состоит из одинаковых имен. Что вам нужно сделать, так это добавить индекс к имени при создании фигур

Это сработает:

 Sub test()
    
   
    Const cntShapes As Long = 2
    
    
    Dim i As Long, shp As Shape, cTarget As Range
    Dim arrShapeNames(1 To cntShapes) As Variant
    
    With Sheet1
        For i = 1 To cntShapes
            Set cTarget = .Cells(1, i)   'adjust this to your needs
            Set shp = .Shapes.AddShape(msoShapeRectangle, cTarget.Left, cTarget.Top, 50, 50)
            shp.Name = "MyShape." amp; i   'adding the index to the name makes it unique
            arrShapeNames(i) = shp.Name
        Next
    End With
    
    
    ' Group Shapes
    Dim ShapeGroup As Shape
    Set ShapeGroup = Sheet1.Shapes.Range(arrShapeNames).Group

End Sub
 

Комментарии:

1. Эта идея великолепна. Я бы улучшил его до shp.Name = shp.Name amp; shp.ID . Таким образом, он будет работать лучше, если некоторые фигуры будут удалены.

2. Извините — я не вижу проблемы с использованием i-индекса, но также можно добавить идентификатор формы. Если этот ответ является хорошим решением вашего вопроса, было бы неплохо, если бы вы выбрали его в качестве «ответа» — спасибо

Понравилась статья? Поделить с друзьями:
  • Vba excel shape no fill
  • Vba excel set sheet
  • Vba excel set font
  • Vba excel set activeworkbook
  • Vba excel selection что это