Access VBA Macro Programming

(Joao Candeias) #1

strFilter = "Text Files (.txt)" & Chr( 0 ) & ".TXT" & Chr( 0 )
MyFile.lpstrFilter = strFilter
MyFile.nFilterIndex = 1
MyFile.lpstrFile = String(257, 0 )
MyFile.nMaxFile = Len(MyFile.lpstrFile) - 1
MyFile.lpstrFileTitle = MyFile.lpstrFile
MyFile.nMaxFileTitle = MyFile.nMaxFile
MyFile.lpstrInitialDir = "C:\"
MyFile.lpstrTitle = "Select a File"
MyFile.flags = 0
ReturnValue = GetOpenFileName(MyFile)
If ReturnValue = 0 Then
MsgBox "Cancel Button was pressed"
Else
MsgBox MyFile.lpstrFile
End If
End Sub


This procedure sets up a variable called MyFile based on the data type OPENFILENAME
and variables to hold the return value from the API call and a string value to hold the filter
for the file selection. The MyFile object is then populated with the parameters needed to
display the file dialog such as flags, initial directory, and title. The dialog box is then called
by using the function GetOpenFileName based on the variable of MyFile. This populates the
variable ReturnValue, which holds True or False depending on whether a file was selected.
If the file was selected, the variable MyFile.lpstrfile returns the name.
Notice that the handle property (hwnd) of your form is used to populate Myfile.hwndOwner.
This is why the API call has to work from a form or report.
You can also change the filter to the needs of your application very easily. Currently, this
sets it to text files only, but this can be changed to other options. This is so that when the
dialog opens you can restrict it to certain types of files such as text. This is important if you
are using the dialog to allow the user to select a file for importing into your database.
This procedure also supplies the starting folder and provides a title for the dialog. Finally,
the API call is made, placing a value into the variable ReturnValue. If this value is zero, then
the user pressed the Cancel button, but if it had a value, then a file was selected that is held in
MyFile.lpstrFile.
You then call this subroutine from your command button. This assumes you have added
the following code to a module and that the command button you are using is called
Command0:


Private Sub Command0_Click()
ShowFileDialog
End Sub


Bear in mind that the dialog only selects the file for you. You will need to write further
code to open and process the file.


Chapter 10: Common Dialog Control 125

Free download pdf