Shape names in excel

When a picture is inserted into an Excel worksheet using Shapes.AddPicture(…) method, Excel gives it a name «Picture 1», «Picture 2» etc automatically.

This name can be used to get a reference to this shape object in Shapes collection like Shapes.Item(«Picture 1»). If the name is changed in Excel using the Name Box, there are two different names (or one of them is a key/Caption) through which the Shape object can be referenced. So if I change the name to «MyPic» I can use any of these to reference a shape in Shapes collection:

Shapes.Item("Picture 1")
OR
Shapes.Item("MyPic")

The name can be accessed using Shape.Name property in VBA but how can we access the other value (MyPic) that does not seem to change internally?

UPDATED
What I am trying to do is to link a cell to a picture in Excel. I keep the picture data in cell’s comment. These are the scenarios:

  1. If I keep the picture name (external name) then copy-pasting the structure on the same worksheet will duplicate the name and the cell will point to the same structure.
  2. If I keep the internal name then copy-pasting to other worksheet will create problem as the same internal name can exist on some other worksheet in the same workbook.
  3. If I take ID, I will not be able to get the Picture reference from it

For me getting the internal name is important. I have the Shape reference but no idea how to get the internal name from this ref.

Community's user avatar

asked Sep 19, 2010 at 8:12

A9S6's user avatar

Immediately after you have added the shape to a worksheet (oSht) you can use oSht.Shapes(Osht.Shapes.count) to reference it.
So, oSht.Shapes(osht.shapes.count).Name will give you its name.

If you want to find the index of a shape in the Shapes collection and you know its name then you need to loop through Shapes.Name until you find it. If you know the Index, then you can construct the «Picture n» alternate name, or you can store the «Picture n» alternate name. You can also store the ID property of the shape and then reference the shape by looping through the Shapes collections until you find the Shape.ID

If the user moves the shape to a different sheet and then renames it, there is no way of identifying it as the original shape, because the external name, alternate name, Shapes index, and ID will all be different. So, if this is a problem in your scenario you would need to consider shadow copying or sheet protection.

RGA's user avatar

RGA

2,55219 silver badges38 bronze badges

answered Sep 19, 2010 at 16:45

Charles Williams's user avatar

Charles WilliamsCharles Williams

23.1k5 gold badges37 silver badges38 bronze badges

6

Работа с фигурами в 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. Копирование, перемещение и поворот фигур.


Содержание

  1. Shape object (Excel)
  2. Remarks
  3. Example
  4. Methods
  5. Properties
  6. See also
  7. Support and feedback
  8. Объект Shape (Excel)
  9. Замечания
  10. Пример
  11. Методы
  12. Свойства
  13. См. также
  14. Поддержка и обратная связь
  15. Shapes object (Excel)
  16. Remarks
  17. Example
  18. Methods
  19. Properties
  20. See also
  21. Support and feedback
  22. Объект Shapes (Excel)
  23. Замечания
  24. Пример
  25. Методы
  26. Свойства
  27. См. также
  28. Поддержка и обратная связь
  29. How to get Shape’s internal name in Excel

Shape object (Excel)

Represents an object in the drawing layer, such as an AutoShape, freeform, OLE object, or picture.

The Shape object is a member of the Shapes collection. The Shapes collection contains all the shapes in a workbook.

There are three objects that represent shapes: the Shapes collection, which represents all the shapes on a workbook; the ShapeRange collection, which represents a specified subset of the shapes on a workbook (for example, a ShapeRange object could represent shapes one and four in the workbook, or it could represent all the selected shapes in the workbook); and the Shape object, which represents a single shape on a worksheet. If you want to work with several shapes at the same time or with shapes within the selection, use a ShapeRange collection.

To return. Use.
A Shape object that represents one of the shapes attached by a connector The BeginConnectedShape or EndConnectedShape property of the ConnectorFormat object.
A newly created freeform The BuildFreeform and AddNodes methods to define the geometry of a new freeform, and use the ConvertToShape method to create the freeform and return the Shape object that represents it.
A Shape object that represents a single shape in a grouped shape GroupItems (index), where index is the shape name or the index number within the group.
A newly formed group of shapes The Group or Regroup method of the ShapeRange object to group a range of shapes and return a single Shape object that represents the newly formed group. After a group has been formed, you can work with the group the same way that you work with any other shape.
A Shape object that represents an existing shape Shapes (index), where index is the shape name or the index number.
A Shape object that represents a shape within the selection Selection.ShapeRange (index), where index is the shape name or the index number.

Example

The following example horizontally flips shape one and the shape named Rectangle 1 on myDocument.

Each shape is assigned a default name when you add it to the Shapes collection. To give the shape a more meaningful name, use the Name property. The following example adds a rectangle to myDocument, gives it the name Red Square, and then sets its foreground color and line style.

The following example sets the fill for the first shape in the selection in the active window, assuming that there’s at least one shape in the selection.

Methods

Properties

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.

Источник

Объект Shape (Excel)

Представляет объект в слое рисования, например автофигуру, свободную форму, объект OLE или рисунок.

Замечания

Объект Shape является членом коллекции Shapes . Коллекция Shapes содержит все фигуры в книге.

Есть три объекта, которые представляют фигуры: коллекция Shapes , которая представляет все фигуры в книге; коллекция ShapeRange , представляющая указанное подмножество фигур в книге (например, объект ShapeRange может представлять фигуры одной и четырех в книге или может представлять все выбранные фигуры в книге); и объект Shape , представляющий одну фигуру на листе. Если вы хотите работать с несколькими фигурами одновременно или с фигурами в выделенном фрагменте, используйте коллекцию ShapeRange .

Чтобы вернуться. Использовать.
Объект Shape , представляющий одну из фигур, присоединенных соединителем Свойство BeginConnectedShape или EndConnectedShape объекта ConnectorFormat .
Только что созданная свободная форма Методы BuildFreeform и AddNodes определяют геометрию новой свободной формы и используют метод ConvertToShape для создания свободной формы и возврата объекта Shape , представляющего ее.
Объект Shape , представляющий одну фигуру в сгруппированной фигуре GroupItems (index), где индекс — это имя фигуры или номер индекса в группе.
Вновь сформированная группа фигур Метод Group или Regroup объекта ShapeRange для группировки диапазона фигур и возврата одного объекта Shape , представляющего только что сформированную группу. После формирования группы вы можете работать с ней так же, как с любой другой фигурой.
Объект Shape , представляющий существующую фигуру Фигуры (индекс), где индекс — это имя фигуры или номер индекса.
Объект Shape , представляющий фигуру в выделенном фрагменте Выделение. ShapeRange (index), где индекс — это имя фигуры или номер индекса.

Пример

В следующем примере по горизонтали фигура 1 и фигура с именем Rectangle 1 в myDocument.

Каждой фигуре присваивается имя по умолчанию при ее добавлении в коллекцию Фигуры . Чтобы придать фигуре более понятное имя, используйте свойство Name . В следующем примере в myDocument добавляется прямоугольник, ему присваивается имя Красный квадрат, а затем задается цвет переднего плана и стиль линии.

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

Методы

Свойства

См. также

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

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

Источник

Shapes object (Excel)

A collection of all the Shape objects on the specified sheet.

Each Shape object represents an object in the drawing layer, such as an AutoShape, freeform, OLE object, or picture.

If you want to work with a subset of the shapes on a document—for example, to do something to only the AutoShapes on the document or to only the selected shapes—you must construct a ShapeRange collection that contains the shapes that you want to work with.

Example

Use the Shapes property of the Worksheet object to return the Shapes collection. The following example selects all the shapes on myDocument.

If you want to do something (like delete or set a property) to all the shapes on a sheet at the same time, select all the shapes, and then use the ShapeRange property on the selection to create a ShapeRange object that contains all the shapes on the sheet, and then apply the appropriate property or method to the ShapeRange object.

Use Shapes (index), where index is the shape’s name or index number, to return a single Shape object. The following example sets the fill to a preset shade for shape one on myDocument.

Use Range (index), where index is the shape’s name or index number or an array of shape names or index numbers, to return a ShapeRange collection that represents a subset of the Shapes collection. The following example sets the fill pattern for shapes one and three on myDocument.

An ActiveX control on a sheet has two names: the name of the shape that contains the control, which you can see in the Name box when you view the sheet, and the code name for the control, which you can see in the cell to the right of (Name) in the Properties window. When you first add a control to a sheet, the shape name and code name match. However, if you change either the shape name or code name, the other isn’t automatically changed to match.

You use the code name of a control in the names of its event procedures. However, when you return a control from the Shapes or OLEObjects collection for a sheet, you must use the shape name, not the code name, to refer to the control by name. For example, assume that you add a check box to a sheet and that both the default shape name and the default code name are CheckBox1. If you then change the control code name by typing chkFinished next to (Name) in the Properties window, you must use chkFinished in event procedures names, but you still have to use CheckBox1 to return the control from the Shapes or OLEObject collection, as shown in the following example.

Methods

Properties

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.

Источник

Объект Shapes (Excel)

Коллекция всех объектов Shape на указанном листе.

Замечания

Каждый объект Shape представляет объект на слое рисования, например автофигуру, свободную форму, объект OLE или рисунок.

Если вы хотите работать с подмножеством фигур в документе( например, для выполнения действий только с автофигурами в документе или только с выбранными фигурами), необходимо создать коллекцию ShapeRange , содержащую фигуры, с которыми вы хотите работать.

Пример

Используйте свойство Shapes объекта Worksheet , чтобы вернуть коллекцию Shapes . В следующем примере выбраны все фигуры в myDocument.

Если вы хотите выполнить что-то (например, удалить или задать свойство) для всех фигур на листе одновременно, выделите все фигуры, а затем используйте свойство ShapeRange в выделенном фрагменте, чтобы создать объект ShapeRange , содержащий все фигуры на листе, а затем применить соответствующее свойство или метод к объекту ShapeRange .

Используйте фигуры (индекс), где индекс — это имя или номер индекса фигуры, чтобы вернуть один объект Shape. В следующем примере заливка задает предустановленный оттенок для фигуры 1 в myDocument.

Используйте диапазон (индекс), где индекс — это имя или номер индекса фигуры или массив имен фигур или номеров индексов, чтобы вернуть коллекцию ShapeRange , представляющую подмножество коллекции Shapes . В следующем примере задается шаблон заливки для фигур один и три в myDocument.

Элемент ActiveX на листе имеет два имени: имя фигуры, содержащей элемент управления, которое отображается в поле Имя при просмотре листа, и кодового имени элемента управления, которое отображается в ячейке справа от (Имя) в окно свойств. При первом добавлении элемента управления на лист имя фигуры и код совпадают. Однако при изменении имени фигуры или кодового имени другое не будет автоматически изменено в соответствии с ней.

Имя кода элемента управления используется в именах его процедур событий. Однако при возврате элемента управления из коллекции Shapes или OLEObjects для листа необходимо использовать имя фигуры, а не код, чтобы ссылаться на элемент управления по имени. Например, предположим, что вы добавили флажок на лист и что имя фигуры по умолчанию и код по умолчанию — CheckBox1. Если изменить имя кода элемента управления, введя chkFinished рядом с (Name) в окно свойств, необходимо использовать chkFinished в именах процедур событий, но по-прежнему необходимо использовать CheckBox1 для возврата элемента управления из коллекции Shapes или OLEObject, как показано в следующем примере.

Методы

Свойства

См. также

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

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

Источник

How to get Shape’s internal name in Excel

When a picture is inserted into an Excel worksheet using Shapes.AddPicture(. ) method, Excel gives it a name «Picture 1», «Picture 2» etc automatically.

This name can be used to get a reference to this shape object in Shapes collection like Shapes.Item(«Picture 1»). If the name is changed in Excel using the Name Box, there are two different names (or one of them is a key/Caption) through which the Shape object can be referenced. So if I change the name to «MyPic» I can use any of these to reference a shape in Shapes collection:

The name can be accessed using Shape.Name property in VBA but how can we access the other value (MyPic) that does not seem to change internally?

UPDATED
What I am trying to do is to link a cell to a picture in Excel. I keep the picture data in cell’s comment. These are the scenarios:

  1. If I keep the picture name (external name) then copy-pasting the structure on the same worksheet will duplicate the name and the cell will point to the same structure.
  2. If I keep the internal name then copy-pasting to other worksheet will create problem as the same internal name can exist on some other worksheet in the same workbook.
  3. If I take ID, I will not be able to get the Picture reference from it

For me getting the internal name is important. I have the Shape reference but no idea how to get the internal name from this ref.

Источник

How to create autoshapes, lines and connectors in VBA macros

Part three 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
  3. Naming, referring to and positioning shapes (this blog)
  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.

Once you’ve added a shape, you’ll want to be able to refer to it in the
future — and you’ll also need to know how to position it exactly where you want
on the screen.

Adding a shape without getting a reference to it

Consider the following block of code, which adds a square to the current
worksheet:

Sub AddSquare()

Dim ws As Worksheet

Set ws = ActiveSheet

ws.Shapes.AddShape 1, 50, 50, 100, 100

End Sub

The problem with this method is that there’s no easy way to refer to the
shape after adding it.  If it’s the only shape added to date, this would
work:

However, referring to a shape by its index number within the collection of
shapes clearly isn’t a reliable method. 

Adding a shape while at the same time getting a reference to it

A much better way to add a shape is by setting an object variable to refer to
it immediately after adding it:

Sub AddSquare()

Dim ws As Worksheet

Dim sq As Shape

Set ws = ActiveSheet

Set sq = ws.Shapes.AddShape(1, 50, 50, 100, 100)

sq.Name = «WOL_0001»

End Sub

Note that (as always in VBA) if you’re capturing a reference to something,

you need to include brackets round the argument list.  The advantage of
the above approach is that you can now refer to the shape that’s been added either by
the object variable used:

Or by its name:

ws.Shapes(«WOL_0001»).Left = 300

Shape names are a bit strange in VBA, and are not necessarily unique. 
Rather than trying to understand the rules, the simplest thing is to generate
and assign unique names yourself for shapes that you’ve created
programmatically.

Positioning shapes relative to cells

You’ve already seen that when you position a shape you do it relative to the
top left corner of a worksheet.  However, it’s easy enough to change this
to position a shape relative to a cell:

Shape position

To position a shape in the shaded cell, we just need to know the two distances shown.

For example, supposing that we want to add a shape within the cell like this:

Shape within cell

The shape is half the width of the cell, and half its height.

Here’s some sample code to do this:

Sub AddShapeToCell()

Dim c As Range

Dim ws As Worksheet

Set ws = ActiveSheet

Set c = Range(«B4»)

ws.Shapes.AddShape Type:=msoShape10pointStar, _

Left:=c.Left + (c.Width / 4), _

Top:=c.Top + (c.Height / 4), _

Width:=c.Width / 2, _

Height:=c.Height / 2

End Sub

This code will position the shape relative to the top left corner of the
cell, rather than of the worksheet.

One thing to watch is that the units for column widths/row heights aren’t the
same as for shapes!

Now that we know how to refer to our shapes (and how to position them where
we want on screen), it’s time to make them look pretty!

This blog has 1 thread

Add post

11 Feb 21 at
22:38

This post has been very helpful.

I’ve used the sq.Name = WOL_0001 in my script and it works great for referencing the objects in the code. Once the macro completes is there a command to clear the assigned names from the objects on the sheet so that they can be used again for the next iteration?

My specific code is grouping the objects with user-defined info to be used in a visual layout.  When the code is run on the next set of information it works fine until it goes to group the objects; at this point it errors because it’s selecting all the already named objects from the first pass, and these are already grouped, causing of the error. The underlying issue is the code is selecting the wrong objects after the first pass. Once they are grouped I have no need for the assigned name reference anymore and need to start the code over.

  • #1

Hi everyone,
this is probably really simple but I now starting to get really feed up with it,
I have a load of shapes with names and I want to rename them now I know you can click on them but lots oof these shapes are on top of each other so it takes ages click sending to back and so on just to get to a shape to name it,

is there a place in excel that has the shapes all listed that I can edit from?

if so how do I find it?

thanks

Tony

How to change case of text in Excel?

Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won’t capitalize second c in Mccartney

  • #2

Hi,

I think if you know the name of a shape you can enter it into the Name Box and over-type it.

If you don’t know the name then you will have to select it.

You could have a macro that listed all the names on a worksheet. You could then enter your preferred name alongside and have another macro to make the changes.

Thinking about it, you might like something like this:

Code:

Sub ShapeRename()

    Dim ws As Worksheet
    Dim sh As Shape
    Dim newName As Variant

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    With ws

        For Each sh In .Shapes
            sh.Select
            ws.Activate
            newName = Application.InputBox(Prompt:="Enter new name for shape: " & sh.Name, Title:="Change Shape Names", Type:=2)
            If newName = "" Then Exit Sub
            sh.Name = newName
        Next

    End With

End Sub

The code needs to be pasted into a new Module.
The worksheet name is currently Sheet1 but can be overtyped.

It loops through the shapes on a worksheet.
It selects it so you can see which it is then prompts for a new name while quoting the old one.
If you enter a valid one it will change it.
Entering a null response will end the macro.

  • #3

Hi Rickxl

That is brilliant, it will do exactly as I want,
massive thank you once again for your time and your help this will solve my problem

Thanks

Tony

  • #4

No problem — all part of the excellent MrExcel service :)

You were lucky, as I was writing the reply I had one of those «Hey, what if …?» moments.

Thanks for the feedback.

  • #5

Well your Hey what if moment has saved me hours of work today which means I will get to the pub later so thank you very much indeed :)

Thats quite a few times recently your code has helped me so thank you so much

Tony

  • #6

Happy to be of service …
… and talking of pubs (y)

Regards,

  • #7

Just like to say thank you sorted me out to.

Понравилась статья? Поделить с друзьями:
  • Shape name in excel vba
  • Shane from the l word
  • Shan is a word
  • Shamrock symbol in word
  • Shall i have a word with you