Home » excel » excel – Replace an existing image with a new image

excel – Replace an existing image with a new image

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’ve made a real estate related worksheet that includes a few cells for the property’s address and a picture of a Google Maps view of the property. I want to be able to change the address in the worksheet and then click the image to have it refresh with a map of the new address. I can’t figure out how to replace the image.

Here’s what I’ve got so far:

Function scrub(s As String)
    scrub = Replace(s, " ", "+")
    scrub = Replace(scrub, ",", "")
End Function

Function GetImageAddress(rng As Range)
    Dim cell As Range
    Dim addressString As String
    addressString = ""
    For Each cell In rng
        If cell.Value <> "" Then
            If addressString <> "" Then
                addressString = addressString & "+" & scrub(cell.Value)
            Else
                addressString = scrub(cell.Value)
            End If
        End If
    Next cell

    Dim urlstart, urlmid, urlend, key As String

    key = "API_KEY" 'you'll need to get your own Google API Key for this to work
    urlstart = "https://maps.googleapis.com/maps/api/staticmap?center="
    urlmid = "&markers=color:0x359BB2%7C"
    urlend = "&zoom=17&size=640x480&scale=3&maptype=hybrid&key=" & key

    GetImageAddress = urlstart & addressString & urlmid & addressString & urlend
End Function

Sub fetchImage()
    Dim rng As Range
    Set rng = ActiveSheet.Range("E10:E12")

    Dim url As String
    url = GetImageAddress(rng)

    Dim myImage As Shape
    Set myImage = ActiveSheet.Shapes("Map")

    'something should go here to replace myImage with a new downloaded picture.

End Sub
How to&Answers:

Use the .Fill.UserPicture property

myImage.Fill.UserPicture url

Here is an example

Option Explicit

Sub Sample()
    Dim url As String
    Dim myImage As Shape

    url = "https://lh4.googleusercontent.com/-X3sAhOMOHzs/AAAAAAAAAAI/AAAAAAAADMM/dTqQjEqFDm4/photo.jpg?sz=32"

    Set myImage = ActiveSheet.Shapes(1)
    myImage.Fill.UserPicture url
End Sub

will fill the shape with your stackoverflow DP.

enter image description here

Note: This won’t work if the original shape was an inserted picture. Insert a new shape like a rectangle, and then this will work.