Search code examples
excelvbaif-statementcaseshapes

Change background image of Shape by clicking on Shape


I'm looking for VBA code that will cycle through background images (saved on my computer) shown within a Shape by clicking on the Shape.

I found two sets of code that give me a good start but I can't figure out how to merge the code to get the result I'm looking for.

I want each click on a Shape to keep cycling through the following command:

  1. Initial Shape: transparent background
  2. Single Click on Shape: Transparent background replaced with BackgroundImage1
  3. Another Single Click on Shape: BackgroundImage1 replaced with BackgroundImage2
  4. Another Single Click on Shape: BackgroundImage2 replaced with transparent background

I found this code to change color of the Shape by clicking:

Sub trafficlight()
    Dim WhoAmI As String, sh As Shape
    WhoAmI = Application.Caller
    With ActiveSheet.Shapes(WhoAmI).Fill.ForeColor
        Select Case .RGB
            Case vbRed
                .RGB = vbGreen
            Case vbGreen
                .RGB = vbYellow
            Case Else
                .RGB = vbRed
        End Select
    End With
End Sub

And this code to change the Shape with an image saved on my computer:

Sub Rectangle9_Click()
    Dim WhoAmI As String, sh As Shape
    WhoAmI = Application.Caller
    With ActiveSheet.Shapes(WhoAmI).Fill
        .Visible = msoTrue
        .UserPicture "C:\Users\username\Desktop\BackgroundImage1.png"
        .TextureTile = msoFalse
    End With
End Sub

Solution

  • You need to keep track of what image is currently displayed. You could set an integer for each time the image changes.

    Option Explicit
    
    Sub ChangeShapePic()
    Static i As Integer
    
    With ActiveSheet.Shapes(Application.Caller).Fill
        Select Case i
            Case 0
                .UserPicture ("C:\Users\username\Desktop\BackgroundImage1.png")
                i = 1
            Case 1
                .UserPicture ("C:\Users\username\Desktop\BackgroundImage2.png")
                i = 2
            Case 2
                .UserPicture ("C:\Users\username\Desktop\BackgroundImage3.png")
                i = 3
            Case 3
               .Solid
               .Transparency = 0#
                i = 0
        End Select
    End With
    End Sub