Search code examples
excelvba

Delete the previous image in Excel VBA


An image is populated correctly when I click the value.

When I click on the image, the previous image has to be deleted.

I tried a delete code.

Private Sub ShowValues()
Dim a As String
Dim Var As String
Dim Var2 As String
Dim insert_path As String
Dim pic As Picture

'Delete Code
For Each pic In ActiveSheet.Pictures
    If Not Application.Intersect(pic.TopLeftCell, Range("H10:R24")) Is Nothing Then
        pic.Delete
    End If
Next pic

Range("C1").Value = ActiveCell.Value
'a = Range("C1").Value
Var = "********" 'drivepath
'MsgBox (Range("B" & j).Value)
Var2 = Range("C1").Value
insert_path = Var & "\" & Var2

Call ActiveSheet.Shapes.AddPicture(insert_path, _
  msoCTrue, msoCTrue, 400, 160, 800, 600)
End Sub

Solution

  • You can use several ways to identify a shape. Problem by identify it by the cell Range or it's Top/Left property is that this might change if the user moves the image around or resize some cells, so at the end of the day this is not reliable.

    I would suggest you name the shape holding the picture after inserting it. Now before you insert it, check if there is already a shape with that name and remove it (I took the freedom to rename your variables):

    Private Sub ShowValues()
        Const imageShapeName = "MyGreatShapeHoldingAnImage"  ' Whatever you want.
        
        Dim path As String, imageName As String, fullName As String
        
        With ActiveSheet
            .Range("C1").Value = ActiveCell.Value
            path = "********" 'drivepath
            imageName = Range("C1").Value
            fullName = path & "\" & imageName
        
            Dim pic As Shape
            On Error Resume Next
            Set pic = .Shapes(imageShapeName)
            On Error GoTo 0
            If Not pic Is Nothing Then pic.Delete
        
            Call .Shapes.AddPicture(fullName, msoCTrue, msoCTrue, 400, 160, 800, 600)
            Set pic = .Shapes(.Shapes.Count)
            pic.Name = imageShapeName
        End With
    End Sub