Search code examples
excelvbaimageuserform

Is it possible to programmatically add an image file to an image or commandbutton control in a vba userform?


I am trying to get a image to load programmatically into image and commandbutton MSForms controls to no avail without the VB editor. I am using the macro structure below which works well with other controls. Microsoft indicates here that the editor must be used:

You must use the control's property page to assign a bitmap to the Picture property. You cannot use the Visual Basic LoadPicture function to assign a bitmap to Picture.

The macro below works when the .Picture command is commented out without image of course. When loading an image into a commandbutton the same problem occurs. I have tried various ways to provide the file location but it always errors out. Does someone know a clever work around?

Sub NewForm()

Dim TempForm As Object
Dim NewImage As MSForms.Image

Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)
With TempForm
 .Properties("Height") = 300
 .Properties("Width") = 300
End With

Set NewImage = TempForm.designer.Controls.Add("Forms.image.1")
With NewImage
 .Picture = "C:\image.jpg"  'Nothing works here it seems
 .Height = 100
 .Left = 100
 .Top = 100
 .Width = 100
End With

End Sub

Solution

  • Below is an example to add Images to Image and Command Button.

    Three changes that I made

    1. I changed Dim NewImage As MSForms.Image to Dim NewImage As Object. Using Dim NewImage As Image will also work.
    2. I used an image from my pc.
    3. I used LoadPicture().

    Is this what you are trying?

    Option Explicit
    
    Sub NewForm()
        Dim TempForm As Object
        Dim NewImage As Object
    
        Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)
        With TempForm
            .Properties("Height") = 300
            .Properties("Width") = 300
        End With
        
        '~~> Image Control
        Set NewImage = TempForm.designer.Controls.Add("Forms.image.1")
        With NewImage
            .Picture = LoadPicture("C:\Users\routs\Desktop\Start.Bmp")
            .Height = 100
            .Left = 100
            .Top = 10
            .Width = 100
        End With
        
        '~~> Command Button
        Dim ctl_Command As Control
        Set ctl_Command = TempForm.designer.Controls.Add("Forms.CommandButton.1", "CmdXYZ", False)
        
        With ctl_Command
            .Picture = LoadPicture("C:\Users\routs\Desktop\Start.Bmp")
            .Left = 100
            .Top = 140
            .Height = 50
            .Width = 50
            .Visible = True
        End With
    End Sub
    

    In Action

    enter image description here