UserForm Controls - Image and RefEdit
UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of "Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet".
Also refer "2. UserForm and Controls - Properties" for properties common to the UserForm and most Controls
Note: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.
-----------------------------------
Contents:
-----------------------------------
Image control is used to display a Picture on the UserForm. The first step is to add an Image control to the UserForm. To assign a picture to this control at design time, specify a picture using the "Picture" property, which will display it in the UserForm. To remove a picture, press DELETE in the value field of "Picture" property in Properties window (Note: pressing BACKSPACE will not remove the picture). You can assign a picture to the Image control at run time by using the LoadPicture function, as shown below. An important aspect is to fit a picture in the Image control or adapt the control's size to the picture, which determines how the picture will get displayed. This can be done using the PictureSizeMode Property as described below.
PictureSizeMode Property: Specifies how the picture will be displayed viz. in relation to its original size and scale. There are 3 settings: (i) fmPictureSizeModeClip (value 0) - this is the default value and it clips that part of the picture which is larger than its container ie. the Image control; (ii) fmPictureSizeModeStretch (value 1) - stretches the picture to fit its container ie. the Image control, and might distort the picture horizontally or vertically; (iii) fmPictureSizeModeZoom (value 3) - enlarges (does not distort) the picture - picture is enlarged till it first reaches the horizontal or vertical limit of its container (ie. Image control). If the horizontal limit is reached first, then the remaining vertical space will appear blank and if the vertical limit is reached first, then the remaining horizontal space will appear blank. PictureSizeMode property can be set in the Properties window and can also be used with a macro or vba code.
PictureAlignment Property: Specifies the relative position or alignment of the picture within the Image control. There are 5 settings: (i) fmPictureAlignmentTopLeft (value 0); (ii) fmPictureAlignmentTopRight (value 1); (iii) fmPictureAlignmentCenter (value 2); (iv) fmPictureAlignmentBottomLeft (value 3); and (v) fmPictureAlignmentBottomRight (value 4). The settings are self-explanatory viz. fmPictureAlignmentBottomLeft setting means that picture aligns at the bottom left corner of the Image control. Note: If the image is set to fmSizeModeStretch (in its PictureSizeMode property) the picture stretches to fit its container/Image control, then the PictureAlignment property does not have any effect.
Using the LoadPicture function to assign a picture to the Image control at run time:
Syntax: ImageControl.Picture = LoadPicture(pathname)
Example 1: Select picture from ListBox to display in Image control - refer Image 31. See below code:
Private Sub UserForm_Initialize()
'Add items in ListBox:
ListBox1.AddItem "picture1"
ListBox1.AddItem "picture2"
ListBox1.AddItem "picture3"
ListBox1.AddItem "picture4"
End Sub
Private Sub ListBox1_Click()
'select picture from list to display in Image control:
If ListBox1.Value = "picture1" Then
Image1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage1.jpg")
ElseIf ListBox1.Value = "picture2" Then
Image1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage2.jpg")
ElseIf ListBox1.Value = "picture3" Then
Image1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage3.jpg")
ElseIf ListBox1.Value = "picture4" Then
Image1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage4.jpg")
End If
End Sub
Example 2: Select full path (folder & filename) of a picture from ListBox to display in Image control - refer Image 32. See below code:
Private Sub UserForm_Initialize()
'load ListBox showing full path (folder & filename) of the pictures:
Dim pic1 As String
Dim pic2 As String
Dim pic3 As String
Dim pic4 As String
pic1 = "C:\Project_1\NewPictures\TestImage1.jpg"
pic2 = "C:\Project_1\NewPictures\TestImage2.jpg"
pic3 = "C:\Project_1\NewPictures\TestImage3.jpg"
pic4 = "C:\Project_1\NewPictures\TestImage4.jpg"
ListBox1.AddItem pic1
ListBox1.AddItem pic2
ListBox1.AddItem pic3
ListBox1.AddItem pic4
End Sub
Private Sub ListBox1_Click()
'select picture from list to display in Image control:
Image1.Picture = LoadPicture(ListBox1.List(ListBox1.ListIndex))
End Sub
Example 3: To display a picture in the command button, on activation of UserForm:
Private Sub UserForm_Initialize()
CommandButton1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage1.jpg")
End Sub
Example 4: To display picture in the Image control on clicking the command button:
Private Sub CommandButton1_Click()
'clicking the command button will display a picture in Image control:
With UserForm6
Image1.Picture = LoadPicture("C:\Project_1\NewPictures\TestImage1.jpg")
End With
End Sub
Use LoadPicture property with GetOpenFilename Method
GetOpenFilename Method:
This method enables a user to enter a file name in the standard open dialog box which is displayed. The method does not open any file, it only displays the box to accept the file name, and returns the user-entered name or name of the selected file which might also be a path (ie. folders & file name).
Syntax: expression .GetOpenFilename([FileFilter], [FilterIndex], [Title], [ButtonText], [MultiSelect]). Expression (an Application object) is necessary to inclue, other variants are optional to mention.
FileFilter is a string which specifies the criteria to filter files. It comprises of pairs of strings (ie. a pair for each filter criteria), each part includes the wildcard character and is separated by commas ex. filefilter:="Text Files (*.txt),*.txt,Tiff Files(*.tif),*.tif,JPEG Files(*.jpg),*.jpg". This example of FileFilter specifies 3 criteria of file filters (viz. Text files, Tiff files & JPEG files) and enables a user to enter/select files with extensions .txt. .jpg and .tif only. To include multiple expressions in a single criteria of file filter, use semi-colons to separate each expression ex. filefilter:="JPEG File Interchange Format (*.jpg;*.jpeg;*.jfif;*.jpe),*.jpg;*.jpeg;*.jfif;*.jpe". This example of FileFilter specifies 1 criteria of file filter (of JPEG format) and includes 4 expressions which enables selection of files with extensions .jpg, .jpeg, .jfif & .jpe. Omitting this argument will default to "All Files (*.*),*.*".
FilterIndex is the default criteria of file filter, specified by the index number which ranges from 1 to the number of specified criteria of file fliters. Omitting to mention FilterIndex (or specifying an index number beyond its range) will default to the first criteria of file filter.
Title specifies the title of the dialog box which is displayed on using the GetOpenFilename Method. The default title is "Open" if not specified.
MultiSelect value of True allows multiple-file selection and if set to False (which is also the default value) will allow single file selection.
Example 5: Use LoadPicture property with GetOpenFilename Method to Load Picture to an Image control. Refer Images 33a to 33c. See below codes:
Private Sub UserForm_Initialize()
'set yellow background color of Image control
Me.Image1.BackColor = RGB(255, 255, 0)
Me.Label1.Caption = "Click on the Yellow box to Select & Load Picture"
End Sub
Private Sub Image1_Click()
'use LoadPicture property with GetOpenFilename Method to Load Picture to an Image control.
Dim strFileName As String
'use GetOpenFilename Method to select picture
strFileName = Application.GetOpenFilename(filefilter:="Tiff Files(*.tif;*.tiff),*.tif;*.tiff,JPEG Files (*.jpg;*.jpeg;*.jfif;*.jpe),*.jpg;*.jpeg;*.jfif;*.jpe,Bitmap Files(*.bmp),*.bmp", FilterIndex:=2, Title:="Select a File", MultiSelect:=False)
If strFileName = "False" Then
MsgBox "File Not Selected!"
Else
'load picture to Image control, using LoadPicture property
Me.Image1.Picture = LoadPicture(strFileName)
'after any change vba has to be told to refresh the UserForm for the change to appear
Me.Repaint
'label caption changes after picture is loaded
Me.Label1.Caption = "Picture Loaded"
End If
End Sub
Private Sub CommandButton1_Click()
'clicking "Close" button will unload the UserForm
Unload Me
End Sub
Example 6: Use LoadPicture property with GetOpenFilename Method to Load Picture to an Image control. Refer Images 33a to 33c. See below codes:
Private Sub UserForm_Initialize()
'set yellow background color of Image control
Me.Image1.BackColor = RGB(255, 255, 0)
Me.Label1.Caption = "Click on the Yellow box to Select & Load Picture"
End Sub
Private Sub Image1_Click()
'use LoadPicture property with GetOpenFilename Method to Load Picture to an Image control.
Dim strFltr As String, strTtl As String, strFileName As String
Dim iFltrIndx As Integer
Dim bMltiSlct As Boolean
'set value for variables to be used in GetOpenFilename Method
strFltr = "Tiff Files(*.tif;*.tiff),*.tif;*.tiff,JPEG Files (*.jpg;*.jpeg;*.jfif;*.jpe),*.jpg;*.jpeg;*.jfif;*.jpe,Bitmap Files(*.bmp),*.bmp"
iFltrIndx = 2
strTtl = "Select a File"
bMltiSlct = False
'ChDrive Statement sets the current drive to C
ChDrive "C"
'ChDir statement sets the current directory to C:\Project_1\NewPictures
ChDir "C:\Project_1\NewPictures"
'use GetOpenFilename Method to select picture:
strFileName = Application.GetOpenFilename(strFltr, iFltrIndx, strTtl, , bMltiSlct)
If strFileName <> "False" Then
'load picture to Image control, using LoadPicture property
Me.Image1.Picture = LoadPicture(strFileName)
'after any change vba has to be told to refresh the UserForm for the change to appear
Me.Repaint
'label caption changes after picture is loaded
Me.Label1.Caption = "Picture Loaded"
End If
End Sub
Private Sub CommandButton1_Click()
'clicking "Close" button will unload the UserForm
Unload Me
End Sub
-----------------------------------------------------------------------------------------------------------------------------
The RefEdit control is available only in a VBA UserForm, and allows a user to select a worksheet range from a box, or to type in the range therein. The RefEdit control displays the cell or range address (can be a single cell or a range of contiguous or non-contiguous cells) which a user selects or enters by typing in. To get the cell or range address which is stored in a RefEdit control, use the Value property. A RefEdit control displays the range that you reference and it behaves similar to the built-in Excel reference boxes viz. when you select a function on the excel worksheet, then click ok, you can see the buttons on the right of the argument boxes and on clicking them you can select a worksheet range (the main dialog box collapses here and re-appears when you click the button again).
Example 5: User RefEdit control to select a worksheet range and execute code in the referenced range with CommanButton. Refer Image 34. See below code:
Private Sub CommandButton1_Click()
'clicking on command button performs action on selected range in RefEdit control:
Dim strAddress As String
'select range in RefEdit control
strAddress = RefEdit1.Value
'enter text & background color in selected range
Range(strAddress).Value = "Hello"
Range(strAddress).Interior.Color = RGB(255, 0, 0)
'click yes to close UserForm and no to continue with another selection
If MsgBox("Action Performed, Exit?", vbQuestion + vbYesNo) = vbYes Then
Unload Me
End If
End Sub