VBA code to insert images in excel cannot recognize images that have letters and special characters in the image name

Asked

Viewed 974 times

2

I use the following VBA code to take images from a folder and insert them into a spreadsheet, but the VBA code cannot recognize images that have letters and special characters in the image name, e.g.: (SP20-TP02), if the image name is only number (2020)works perfectly, follows the code:

Public Function getImage(ByVal sCode As String) As String

    Dim sFile As String
    Dim oSheet As Worksheet
    Dim oCell As Range
    Dim oImage As Shape

    Set oCell = Application.Caller ' Célula onde a função foi chamada
    Set oSheet = oCell.Parent      ' Planilha que chamou a função

    ' Procura por uma imagem existente identificada pelo código (que precisa ser único!)
    Set oImage = Nothing
    For i = 1 To oSheet.Shapes.Count
        If oSheet.Shapes(i).Name = sCode Then
            Set oImage = oSheet.Shapes(i)
            Exit For
        End If
    Next i


    ' Se ainda não existir uma imagem com o código, carrega do arquivo e cria-a.
    ' A imagem já é posicionada na exata posição da célula onde a função foi chamada.
    If oImage Is Nothing Then
        sFile = "C:\macro\" & sCode & ".jpg"
        Set oImage = oSheet.Shapes.AddPicture(sFile, msoCTrue, msoCTrue, oCell.Left, oCell.Top, oCell.Width, oCell.Height)
        oImage.Name = sCode

    ' Caso contrário, se a imagem já existir, garante que ela se posiciona e cabe exatamente dentro da célula
    ' (apenas para o caso do usuário ter movido ou redimensionado manualmente a imagem sem querer)
    Else
        With oImage
            .Left = oCell.Left
            .Top = oCell.Top
            .Width = oCell.Width
            .Height = oCell.Height
        End With
    End If

    ' Retorna nada para a célula (afinal, esta é somente uma função de auxílio)
    getImage = ""

End Function

1 answer

0

The problem with your role is that when you insert: =getImage(SP20-TP02) Excel converts SP20-TP02 to SP20-TP2 and understands as a range of cells from column SP and row 20 to column TP row 2, which if empty returns 0.

One way to verify this is to enter the code MsgBox "'" & sCode & "'", which will return as the function is understanding the String inserted inside it.

Solution

1 - Convert the desired value to String format with: =TEXTO("SP20-TP02";"@")

Then the formula stays: =getImage(TEXTO("SP20-TP02";"@"))

2 - Insert the value into a cell and reference in the UDF

If for example the desired code is inserted in cell B1, the formula is: =getImage(B1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.