Home
Manage Your Code
Snippet: Prompt the user for a file name (VBA)
Title: Prompt the user for a file name Language: VBA
Description: Uses the Office 2003 Object libary By adding customized filters, the user will be allowed to search for either text files or Excel workbooks. Views: 2360
Author: Bill Decastro Date Added: 11/1/2008
Copy Code  
1Public Function GetUserFileName(strCaption As String, _
2    Optional InitialFile As String, _
3    Optional bMultiSelect As Boolean = False, _
4    Optional Filetype As MsoFileType = MsoFileType.msoFileTypeNoteItem) As String
5    
6On Error GoTo EH
7
8Const PROC_NAME As String = "GetUserFileName"
9
10Dim FD As FileDialog
11
12'Create a FileDialog object as a File Picker dialog box.

13Set FD = Application.FileDialog(msoFileDialogOpen)
14
15With FD
16    If Not Len(strCaption) = 0 Then
17        .Title = strCaption
18    End If
19    If Len(InitialFile) > 0 Then
20        .InitialFileName = InitialFile
21    End If
22    .AllowMultiSelect = bMultiSelect
23    'Add a filter that includes GIF and JPEG images and make it the first item in the list.

24    .Filters.Clear
25    'will work for text files only

26    If Filetype = MsoFileType.msoFileTypeNoteItem Then
27        '.Filters.Add "Text", "*.txt; *.csv; *.dat", 1

28        .Filters.Add "Text", "*.txt; *.csv; *.dat"
29        
30    Else
31        'will work with Excel workbooks only

32        .Filters.Add "Excel workbooks", "*.xls", 1
33    End If
34
35    'Use the Show method to display the File Picker dialog box and return the user's action.

36    'The user pressed the action button.

37    If .Show = -1 Then
38        GetUserFileName = .SelectedItems(1)
39    Else
40    End If
41End With
42
43exitProc:
44    Set FD = Nothing
45    Exit Function
46EH:
47    'will log the error and then raise an error back to client

48    
49    
50
51End Function
Notes
Must first set a reference to the MS Office object library