Browse for file and set initial folder to search

J

john

I am trying to use the Shell32 Browseforfolder code to browse to a
file. That I can get to work and I can get another version to work to
browse to a folder and to be able to se the initial folder but I cannot
seem to get both to work setting the initial folder to look at and
browsing down to a file.
This is the code which allows me to set the folder:

'First you need to set a reference to the "Microsoft Shell Controls And
Automation" object 'library. In the VBA Editor, go to the Tools menu,
'choose References, and scroll down to this item and put a check next
to it.

Private Const BIF_RETURNONLYFSDIRS As Long = &H1
Private Const BIF_DONTGOBELOWDOMAIN As Long = &H2
Private Const BIF_RETURNFSANCESTORS As Long = &H8
Private Const BIF_BROWSEFORCOMPUTER As Long = &H1000
Private Const BIF_BROWSEFORPRINTER As Long = &H2000
Private Const BIF_BROWSEINCLUDEFILES As Long = &H4000
Private Const MAX_PATH As Long = 260


Function BrowsetoSpecificFolder(Optional Caption As String, _
Optional InitialFolder As String) As String

Dim SH As Shell32.Shell
Dim F As Shell32.Folder

Set SH = New Shell32.Shell
Set F = SH.BrowseForFolder(0&, Caption, BIF_RETURNONLYFSDIRS, _
InitialFolder)

If Not F Is Nothing Then
BrowsetoSpecificFolder = F.Items.Item.Path
End If

End Function


'You can the call the BrowseFolder function with the following code:
Sub callfolder()
Dim FName As String
FName = BrowsetoSpecificFolder("Select a folder", "C:\aatest")
If FName = "" Then
MsgBox "You didn't select a folder"
Else
MsgBox "You selected: " & FName
End If

End Sub

I have tried adding BIF_BROWSEINCLUDEFILES instead of
BIF_RETURNONLYFSDIRS but I get an automation error can't find file.
Can anyone help?
Many thanks
John
 
K

Kou Vang

Are you using this for selecting the file eventually? When I want to browse
for a file I generally use the Dialog box, have you thought about this? You
can use a filter to select specific types of files as well.
 
J

john

Yes I want to find the file. I have used the dialog box but can you
specify a starting folder for it?
 
M

Martin Fishlock

The code that you are using is for folders (directories) only.

Try the getopenfilename method:

Sub filetest()
Dim fileToOpen As Variant
fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen <> False Then MsgBox "Open " & fileToOpen
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top