Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm looking for an easily deployed solution to a problem I am having. I need to present the user with a dialog box that will allow them to browse their computer freely and select a folder or a file. Upon submit, I need the path of selected object passed back to a VBA macro. Any one have a clue?

TIA,
Chad
Posted

1 solution

This is pretty simple, I got this from Excel 2003, you may need to test for later versions, as far as I know it should still work.

VB
Sub cmdOpenFileDialog()
    'Declare a variable as a FileDialog object.
    Dim fd As FileDialog
    'Create a FileDialog object as a File Picker dialog box.
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    'Declare a variable to contain the path
    'of each selected item. Even though the path is a String,
    'the variable must be a Variant because For Each...Next
    'routines only work with Variants and Objects.
    Dim vrtSelectedItem As Variant
    'Use a With...End With block to reference the FileDialog object.
    With fd
        'Use the Show method to display the File Picker dialog box and return the user's action.
        'The user pressed the action button.
        If .Show = -1 Then
            'Step through each string in the FileDialogSelectedItems collection.
            For Each vrtSelectedItem In .SelectedItems
                'vrtSelectedItem is a String that contains the path of each selected item.
                'You can use any file I/O functions that you want to work with this path.
                'This example simply displays the path in a message box.
                MsgBox "The path is: " & vrtSelectedItem
            Next vrtSelectedItem
        'The user pressed Cancel.
        Else
        End If
    End With
    'Set the object variable to Nothing.
    Set fd = Nothing
End Sub


Regards

[Update]
The answer above works well but now that I am here at work I see I've been using GetOpenFilename method to open files that I wish to import data from.

VB
fileToOpen = Application _
    .GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen <> False Then
    MsgBox "Open " & fileToOpen
End If


This is quicker because you can specify filters in the method call, the above example filters for just text files.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900