Vba excel форма картинки

Добавление изображений на элементы управления пользовательской формы. Свойство Picture. Привязка картинки в редакторе и из кода VBA Excel. Удаление изображения.

Свойство Picture есть у пользовательской формы и некоторых элементов управления: CheckBox, CommandButton, Frame, Image, Label, OptionButton, ToggleButton. Оно позволяет отобразить на этих объектах изображение с расширением jpg, bmp, gif.

Синтаксис

object.Picture = LoadPicture(«pathname»)

  • object – пользовательская форма или подходящий элемент управления;
  • pathname – полный путь к изображению.

Добавление изображений в редакторе VBA

Чтобы добавить картинку на форму или элемент управления в редакторе VBA Excel, необходимо в окне Properties выбранного объекта нажать кнопку с тремя точками в поле значений свойства Picture:

Свойство Picture в окне Properties

Откроется окно проводника, с помощью которого следует выбрать нужное изображение.

Картинка на элементе управления может использоваться вместо надписи или вместе с ней. За выравнивание изображения и положение надписи на объекте отвечает свойство PicturePosition. Подходящее значение свойства PicturePosition проще подобрать в окне Properties выбранного элемента управления.

Добавление изображений из кода VBA Excel

Пример кода VBA Excel, добавляющего надпись и изображение на элемент управления ToggleButton:

Private Sub UserForm_Initialize()

  With ToggleButton1

    .Caption = «Кекс домашний»

    .Picture = LoadPicture(«C:PHOTOkeks.jpg»)

    .PicturePosition = 4

  End With

End Sub

Изображение кекса на пользовательской форме

Программное удаление изображения

Удаляется изображение из элемента управления в коде VBA Excel путем присвоения свойству Picture значения Nothing с помощью ключевого слова Set:

Set CommandButton1.Picture = Nothing

Skip to content

Excel VBA UserForm Image

  • Excel VBA UserForm CheckBox

Image is one of the UserForm control. You can select and drag Image on the UserForm. You can select and drag Image on the UserForm. Image control embeds a picture such as a jpg, jpeg, gif, png, bitmap, etc. It can be used on the UserForm. You can see how it works and more details about Image Control.

  • Load VBA Image_Control on the UserForm
  • Add Dynamic Image_Control on the UserForm Using VBA
  • Delete Image_Control on the UserForm using VBA

VBA Image_Control on the UserForm

Please find more details about VBA ActiveX Image_Control on the UserForm.

    1. Go To Developer Tab and then click Visual Basic from the Code or Press Alt+F11.
    2. Go To Insert Menu, Click UserForm. Please find the screenshot for the same.

Excel VBA UserForm CheckBox

    1. Drag the Image_control on the Userform from the Toolbox. Please find the screenshot for the same.

Image Excel VBA ActiveX Control3

    1. Click on the image_control properties.
    2. On the left side find ‘Picture’ from the available properties of the control.
    3. On the right side click on that, and select image from the source.
    4. On the left side find ‘PictureSizeMode’ from the available properties of the control.
    5. On the right side, select ‘1 – frmPictureSiseModeStretch’ from the available list.
    6. Now, Click ‘F5’ to see the output.
    7. Now, you can see the following output as shown below in the screen shot.

Image Excel VBA ActiveX Control6

Add dynamic Image_Control on the UserForm using VBA

Please find the following steps and example code, it will show you how to add dynamic Image_control on the userform.

    1. Add Image and CommandButton on the userform from the toolbox.
    2. Right click on the CommandButton, click properties
    3. Change the CommandButton caption to ‘Create_Image ’
    4. Double click on the CommandButton
    5. Now, it shows the following code.
Private Sub CommandButton1_Click()
 
End Sub
    1. Call the below procedure named ‘Add_Dynamic_Image ’ and find the below procedure to run.
Private Sub CommandButton1_Click()
    Call Add_Dynamic_Image 
End Sub

Procedure to call in the CommandButton:

Sub Add_Dynamic_Image()
    'Add Dynamic Image and assign it to object 'Img'
    Set Img = UserForm2.Controls.Add("Forms.Image.1")
    
    With Img
        'Load Picture to Image Control
        .Picture = LoadPicture("C:Image  Excel ActiveX Control Object.jpg")  ‘Change Image Path here
        
        'Align the Picture Size
        .PictureSizeMode = fmPictureSizeModeStretch
        
        'Image Position
        .Left = 50
        .Top = 10
    End With
End Sub
    1. Now, click F5 to run the macro, click ‘Create_Image ’ button to see the result.
    2. You can see the created dynamic Image_control which is shown in the following screen shot.

output:

Image Excel VBA ActiveX Control1

Delete Image_Control on the UserForm using VBA

Please find the below code, it will show you how to delete or remove the control on the UserForm. In the below example, its deleting the Image named ‘New Image’ which is on the UserForm named ‘UserForm4’. We can use Remove method to delete the controls which are created during run time. Controls which are created during design time cannot be deleted using this method. Please find the below example and screen shots for better understand.

Code 1: Adding control During Run Time

Private Sub CommandButton1_Click()
    'We can use Add method to add the new controls on run time
    Set lblBtn = Me.Controls.Add("Forms.Image.1")
    With lblBtn
        .Top = 20
        .Left = 40
        .Name = "lblNew1"
    End With
    MsgBox "New Image Control Added"
End Sub

Please find the below screen shot for your reference for the above macro and its output.
When we click on Add Command Button:

Image Excel VBA ActiveX Control7

Code 1: Deleting or Removing Image_control which is created during run time.

Private Sub CommandButton2_Click()
    'We can use Remove method to delete the controls which are created during run time
    'Note: Controls which are created on design time cannot be deleted using this method
    Me.Controls.Remove ("lblNew1")
    MsgBox "Image Control Deleted"
End Sub

Please find the below screen shot for your reference for the above macro and its output.
When we click on Delete Command Button:

Image Excel VBA ActiveX Control8

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
      • In this topic:
  • VBA Image_Control on the UserForm
  • Add dynamic Image_Control on the UserForm using VBA
      • Procedure to call in the CommandButton:
  • Delete Image_Control on the UserForm using VBA

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 2, 2023

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Здравствуйте. Суть в следующем, на Userform создается бокс Image где в процессе использования картинка должна будет меняться в зависимости от вводных данных.
Первый способ который я нашёл это загрузка картинки из указанной папки каждый раз когда используется форма
[vba]

Код

Me.Image1.Picture = LoadPicture(«Адрес к файлу»)

[/vba]
Минус такого способа в том, что папка с файлами должны оставаться в одном месте, а при переносе на другой ПК её вовсе можно забыть скопировать.

Второй вариант, вставить все картинки в Image через окно Properties, команду Picture, и спрятать за границей формы.

Картинки тогда сохраняются в форме и надобность во внешних файлах отпадает, можно просто прописать макросом копировать картинки из спрятанных Image в рабочие.
Но когда картинок много, то выходит нужно с начала каждую отдельно загрузить в Image, затем переименовать его чтоб упрастить поиск нужной картинки, что вылевается в очень долгий процесс.

И вот тут возникает вопрос: есть ли способ загружать в форму картинки, сохранённые на листах?

Well, after searching with google, I found this solution:

For the example you will need:

+----------------+----------------+
| Control        | Name           |
+----------------+----------------+
| User Form      | UserForm1      |
| Image          | Image1         |
| Command Button | CommandButton1 |
+----------------+----------------+

And 2 normal modules, and I use this Names:

+---------------+
| Module Names  |
+---------------+
| Functions_VBA |
| Image_Job     |
+---------------+

Inside the UserForm1 use this code:

Option Explicit

Private Sub CommandButton1_Click()
    Paste_ThePicture 'I will explain later...
     Me.Image1.Picture = LoadPicture(thePath) 'Just this... load the picture
     'If you want to delete the picture from directory
     'Uncomment this:
     'Kill thePath
End Sub

Inside the Image_Job Module put this:

Option Explicit
Public thePath As String

Sub Paste_ThePicture() 'The procedure inside UserForm1
Dim fname As String
Dim objPicture As Variant

    With ActiveSheet.Shapes("Picture 1") 'The name of the picture inside the excel sheet
                                         'you can loop over the pictures or do somenthing
                                         'to take the picture you want
        .CopyPicture xlScreen, xlBitmap
        Set objPicture = PastePicture(xlBitmap) 'Store the picture inside the var
        fname = ThisWorkbook.Path & "" & .Name & ".bmp" 'Create the path for the picture full path
    End With
    thePath = fname 'Store the full path to use it later
SavePicture objPicture, fname 'save the picture in the directory
                              'you can delete it later
                              'Look inside the userForm code
End Sub

And the magic come heres! Inside the Functions_VBA put this:

Option Explicit
Option Compare Text

''' User-Defined Types for API Calls
'Declare a UDT to store a GUID for the IPicture OLE Interface
Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(0 To 7) As Byte
End Type
'Declare a UDT to store the bitmap information
Private Type uPicDesc
    Size As Long
    Type As Long
    hPic As Long
    hPal As Long
End Type

'''Windows API Function Declarations
'Does the clipboard contain a bitmap/metafile?

Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Declare Function CopyImage Lib "user32" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'The API format types we're interested in
Const CF_BITMAP = 2
Const CF_PALETTE = 9
Const CF_ENHMETAFILE = 14
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: PastePicture
'''
''' Purpose:    Get a Picture object showing whatever's on the clipboard.
'''
''' Arguments:  lXlPicType - The type of picture to create.  Can be one of:
'''                          xlPicture to create a metafile (default)
'''                          xlBitmap to create a bitmap
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98   Stephen Bullen      Created
''' 15 Nov 98   Stephen Bullen      Updated to create our own copies of the clipboard images
'''

Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
'Some pointers
Dim h As Long, hPicAvail As Long, hPtr As Long, hPal As Long, lPicType As Long, hCopy As Long
'Convert the type of picture requested from the xl constant to the API constant
lPicType = IIf(lXlPicType = xlBitmap, CF_BITMAP, CF_ENHMETAFILE)
'Check if the clipboard contains the required format
hPicAvail = IsClipboardFormatAvailable(lPicType)
If hPicAvail <> 0 Then
    'Get access to the clipboard
    h = OpenClipboard(0&)
    If h > 0 Then
        'Get a handle to the image data
        hPtr = GetClipboardData(lPicType)
        'Create our own copy of the image on the clipboard, in the appropriate format.
        If lPicType = CF_BITMAP Then
            hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
        Else
            hCopy = CopyEnhMetaFile(hPtr, vbNullString)
        End If
        'Release the clipboard to other programs
        h = CloseClipboard
        'If we got a handle to the image, convert it into a Picture object and return it
        If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, lPicType)
    End If
End If
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: CreatePicture
'''
''' Purpose:    Converts a image (and palette) handle into a Picture object.
'''
'''             Requires a reference to the "OLE Automation" type library
'''
''' Arguments:  None
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98  Stephen Bullen      Created
'''

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture

' IPicture requires a reference to "OLE Automation"
Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture

'OLE Picture types
Const PICTYPE_BITMAP = 1
Const PICTYPE_ENHMETAFILE = 4
' Create the Interface GUID (for the IPicture interface)
With IID_IDispatch
    .Data1 = &H7BF80980
    .Data2 = &HBF32
    .Data3 = &H101A
    .Data4(0) = &H8B
    .Data4(1) = &HBB
    .Data4(2) = &H0
    .Data4(3) = &HAA
    .Data4(4) = &H0
    .Data4(5) = &H30
    .Data4(6) = &HC
    .Data4(7) = &HAB
End With
' Fill uPicInfo with necessary parts.
With uPicInfo
    .Size = Len(uPicInfo)                                                   ' Length of structure.
    .Type = IIf(lPicType = CF_BITMAP, PICTYPE_BITMAP, PICTYPE_ENHMETAFILE)  ' Type of Picture
    .hPic = hPic                                                            ' Handle to image.
    .hPal = IIf(lPicType = CF_BITMAP, hPal, 0)                              ' Handle to palette (if bitmap).
End With
' Create the Picture object.
r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
' If an error occured, show the description
If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)
' Return the new Picture object.
Set CreatePicture = IPic
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: fnOLEError
'''
''' Purpose:    Gets the message text for standard OLE errors
'''
''' Arguments:  None
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98   Stephen Bullen      Created
'''

Private Function fnOLEError(lErrNum As Long) As String
'OLECreatePictureIndirect return values
Const E_ABORT = &H80004004
Const E_ACCESSDENIED = &H80070005
Const E_FAIL = &H80004005
Const E_HANDLE = &H80070006
Const E_INVALIDARG = &H80070057
Const E_NOINTERFACE = &H80004002
Const E_NOTIMPL = &H80004001
Const E_OUTOFMEMORY = &H8007000E
Const E_POINTER = &H80004003
Const E_UNEXPECTED = &H8000FFFF
Const S_OK = &H0
Select Case lErrNum
Case E_ABORT
    fnOLEError = " Aborted"
Case E_ACCESSDENIED
    fnOLEError = " Access Denied"
Case E_FAIL
    fnOLEError = " General Failure"
Case E_HANDLE
    fnOLEError = " Bad/Missing Handle"
Case E_INVALIDARG
    fnOLEError = " Invalid Argument"
Case E_NOINTERFACE
    fnOLEError = " No Interface"
Case E_NOTIMPL
    fnOLEError = " Not Implemented"
Case E_OUTOFMEMORY
    fnOLEError = " Out of Memory"
Case E_POINTER
    fnOLEError = " Invalid Pointer"
Case E_UNEXPECTED
    fnOLEError = " Unknown Error"
Case S_OK
    fnOLEError = " Success!"
End Select
End Function

With all that, you will:

Open the UserForm1 and click the CommandButton1 this will take from the ActiveSheet the shape name «Picture 1» (it is your picture) and Save it in the same path of the Workbook, after that, take that path (the stored picture) and insert it into Image1.
If you want you can delete the picture from the path.

I try to take the picture directly from the clipboard, but I don not know if that is possible, if you can do it, please let me know how you did it, by now this is my help in your question.

Note: I take the magic code from here: Stephen Bullen

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

RefEdit control

———————————— 

Image Control

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_1NewPicturesTestImage1.jpg»)

ElseIf ListBox1.Value = «picture2» Then

Image1.Picture = LoadPicture(«C:Project_1NewPicturesTestImage2.jpg»)

ElseIf ListBox1.Value = «picture3» Then

Image1.Picture = LoadPicture(«C:Project_1NewPicturesTestImage3.jpg»)

ElseIf ListBox1.Value = «picture4» Then

Image1.Picture = LoadPicture(«C:Project_1NewPicturesTestImage4.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_1NewPicturesTestImage1.jpg»
pic2 = «C:Project_1NewPicturesTestImage2.jpg»
pic3 = «C:Project_1NewPicturesTestImage3.jpg»
pic4 = «C:Project_1NewPicturesTestImage4.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_1NewPicturesTestImage1.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_1NewPicturesTestImage1.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_1NewPictures
ChDir «C:Project_1NewPictures»

‘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

——————————————————————————————————————————

RefEdit control

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

Понравилась статья? Поделить с друзьями:
  • Vba excel условие if not
  • Vba excel фильтрация строк
  • Vba excel удалить переменную
  • Vba excel ускорение работы макросов
  • Vba excel удалить папок