Excel VBA: How Check the Name of Picture Inside the Cell?

时光总嘲笑我的痴心妄想 提交于 2020-01-03 02:27:54

问题


I'm writing a program in macro that will check the name of the picture in a cell, then put a value on the next column based on the name of the picture.

My program only checks if the name of the picture exists in the activesheet.

My goal is to check if the name of the picture is on this cell and then put a value on the next column based on the name of the picture. Thanks a lot.

   Sub CheckImageName()
    Dim iRowCountShapes As Integer
    Dim sFindShape As String

    iRowCountShapes = 2


    While Sheets("Data").Cells(iRowCountShapes, 1) <> ""

        If Sheets("Data").Shapes("Rock").Name = "Rock" Then

            Sheets("Data").Cells(iRowCountShapes, 3) = "Rock"

        ElseIf Sheets("Data").Shapes("Roll").Name = "Roll" Then

            Sheets("Data").Cells(iRowCountShapes, 3) = "Roll"

        Else

            Sheets("Data").Cells(iRowCountShapes, 3) = "Neither"

        End If

        iRowCountShapes = iRowCountShapes + 1

    Wend

End Sub

回答1:


Images in Excel can be obsereved as shapes. If they are named correctly(with real filename) on insert then you can iterate through them like this

Private Sub CommandButton1_Click()
Dim doc As Worksheet
Dim spe As Shape

Set doc = Worksheets(1)

For i = 1 To doc.Shapes.Count - 1
    Set spe = doc.Shapes(i)

    'for named images
    Debug.Print doc.Shapes(i).Name

    spe.Select

    'for linked images
    Debug.Print GetSourceInfo(spe)
Next

End Sub

Function GetSourceInfo(oShp As Shape) As String
    On Error GoTo Error_GetSourceInfo
    GetSourceInfo = oShp.LinkFormat.SourceFullName
    Exit Function
Error_GetSourceInfo:
   GetSourceInfo = ""
End Function

Which in my case shows the excel generated imagenames:

  • Picture 1
  • Picture 2
  • Picture 3



回答2:


Pictures aren't reall in cells, they are in the drawing layer above the worksheet. It's easier to just loop through the pictures and put the names in the relevant column based on the cell under the top left corner of the picture:

Sub CheckImageName()
    Dim pic                   As Excel.Picture

    For Each pic In ActiveSheet.Pictures

        pic.TopLeftCell.Offset(, 2).Value2 = pic.Name
    Next pic
End Sub



回答3:


First of all I have to clarify that in my world I do what ever it takes to make things work, so here is my low level approach to getting an objects name.

Record a macro, copy and paste the object anywhere, stop recording. delete the pasted object. View the code for the macro you just created and in the vba you will see the object's name. Delete the macro.



来源:https://stackoverflow.com/questions/32092387/excel-vba-how-check-the-name-of-picture-inside-the-cell

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