Search code examples
imageexcelcontrolsuserformvba

How to clear an Image in a Userform?


I have a Userform in which I use an Image control. I display a picture in this control, based on two criteria.

I don't know how to clear this Image in the Userform when I want to type two new criteria.


Solution

  • You can easily 'clear' your UserForm Image control (e.g. Image1) via Image1.Picture = LoadPicture(vbNullString). In the example below you would switch between showing a defined picture and displaying the empty control when clicking your command button. In order to control the Image status (empty or not) you check the image picture property via If Image1.Picture Is Nothing Then...

    Code example in userform module (Excel)

    Option Explicit
    
    Private Sub CommandButton1_Click()
    ' Purpose: Change view between given image and no image
    Dim sImgName As String                     ' picture name string
    sImgName = "C:\Temp\MyPicture.gif""        ' <<< choose your picture name"
    With Me.Image1
      If .Picture Is Nothing Then             ' picture property has been cleared already
         .Picture = LoadPicture(sImgName)
      Else                                    ' a picture is already displayed
         .Picture = LoadPicture(vbNullString) ' clear it now
      End If
    End With
    End Sub
    

    Hint to use in MS Access

    Note the different use in MS Access repeating @DrMarbuse 's comment as late edit:

    In Access 2010, the picture is directly set by the image path. So LoadPicture() shall not be used anymore (In Excel it is required). Everything stayed the same and worked like a charm.