mdeforge
mdeforge

Reputation: 874

Remember directory last opened from?

I'm writing a Visual Basic application that requires the user to frequently navigate to various directories and open files individually in those locations. Is there a way I can store the location of this directory so that when they choose File -> Open it doesn't just go to the default location and instead remains in the directory they last opened a file from?

Upvotes: 0

Views: 4469

Answers (1)

Matteo NNZ
Matteo NNZ

Reputation: 12685

With FileDialog objects, you have:

1) The property InitialFileName that allows you to set the path to open in the file browser; 2) The SelectedItems property which is a collection of the selected files, storing the last path.

So you can:

a) Declare a global variable called Dim lastPath As String and eventually giving it a default value for the first launch.

b) Write the code to open the File Browser by setting the initial file name:

Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
     '...
    .InitialFileName = lastPath
    '...
End With
fd.Show

c) Save the lastPath each time that the user has selected a file:

With fd
If .Show = -1 Then
    For Each vrtSelectedItem In .SelectedItems
        lastPath = vrtSelectedItem
    Next vrtSelectedItem 
End If
End With

So, the next time you will execute "B" (i.e. you will recall the file browser), you will make sure that the initial file name is the last one the user selected. More info to get started here and here.

Upvotes: 3

Related Questions