Access VBA Macro Programming

(Joao Candeias) #1

The Open File Dialog


The first thing you need to do is enter the module for the form you have created by
right-clicking the form, selecting Build Event from the pop-up menu, and then choosing
Code Builder. This will take you into the VBE window for that form.
Enter the following code into the module in the definitions section at the top:

Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
"GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long

Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type

The purpose of this is to declare the API function called GetOpenFileName and to create a
new data type called OPENFILENAME. The data type is used to hold variables to
manipulate the Open File control.
You then need to create a subroutine to use the API call to display the Open Form dialog
and to return the selection the user has made. Add the following code to your module:

Private Sub ShowFileDialog()
Dim MyFile As OPENFILENAME
Dim ReturnValue As Long
Dim strFilter As String
MyFile.lStructSize = Len(MyFile)
MyFile.hwndOwner = Me.hwnd

124 Microsoft Access 2010 VBA Macro Programming

Free download pdf