How to get Shape's internal name in Excel

两盒软妹~` 提交于 2019-12-14 04:16:58

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3744986/how-to-get-shapes-internal-name-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!