Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Shape's internal name in Excel

Tags:

excel

shapes

vba

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.

like image 434
A9S6 Avatar asked Sep 19 '10 08:09

A9S6


People also ask

Where is the shape name in Excel?

On the Developer tab, in the Shape Design group, click Shape Name.

Where is the shape Format tab in Excel?

Under Text Box Tools, on the Format tab, in the Text Box Styles group, click Change Shape, and then click the shape that you want.


1 Answers

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.

like image 67
Charles Williams Avatar answered Oct 25 '22 22:10

Charles Williams