Question

How do I set a default root folder in the common dialog Select Folder using VBA?

Asked by: WordSpecialisten

In a Excel sheet I have a commandbutton with the text "Select folder", where I want to select a certain root folder, and store the information of the selected subfolder for later use.
By searching the net I found the VBA code shown in the Code section (displays the common dialog Select folder), and it works fine. BUT I want to display the Select folder dialog with a specific root folder on a network, not the Desktop. I then searched again and found some information about the ILCreateFromPath function which should return some kind of structure to use with the pidlRoot property of the SHBrowseForFolder method/function. But I can't find a full VBA example  anywhere, that shows me how to build the code from A to Z. And as I am not familiar with this kind of code I can't use my usual Word VBA logic. I have spent hours trying out different things, but nothing works. I am pretty sure it is very easy for someone who knows averything about common dialogs :-).

So.... can anyone take the code example shown in the Code section and re-write it for me, so that I can display a Select Folder dialog with any folder of my own choice as default root folder? For testpurposes it could be "C:\Officesolutions\MyFiles".

Thank you all very much in advance.

'******** public declaration ********
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
 
'API declarations
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
 
Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
'********* end of public declaration**********
 
'******* Code for the Select Folder command button in the Excel sheet*******
Sub Show_BrowseDirectory_Dialog()
    Dim dirInfo As BROWSEINFO
    Dim path As String
    Dim r As Long, x As Long, pos As Integer
    
    ' Set Default Root folder = Desktop - Here I want to state a specific folder!
    dirInfo.pidlRoot = 0&
    
    dirInfo.lpszTitle = "Browse directory!"
    
    ' Type of directory
    dirInfo.ulFlags = &H1
    
    ' Show the Browse Dialog
    x = SHBrowseForFolder(dirInfo)
    
    ' Parse the result
    path = Space$(512)
    r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
        pos = InStr(path, Chr$(0))
        MsgBox "You have selected :=" & Left(path, pos - 1)
    Else
        MsgBox "Browse a Directory..."
        Show_BrowseDirectory_Dialog
    End If
 
End Sub

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-17 at 06:19:57ID24739679
Tags

Select Folder

,

common dialog

,

default folder

Topic

Microsoft Programming

Participating Experts
1
Points
500
Comments
6

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. VBA
    I AM WRITING IN VBA AND I NEED IT TO USE THE DATA IN A CELL AND ADD OR SUBTACT BY SOME SET NUMBERS. MY PROMBLEM IS THAT I DO NOT NOW HOW TO PULL THE DATA OFF THE SHEET IN EXCEL INTO VBA.
  2. Open File dialog in VBA
    Hi, I want to have a user in an Access 2000 application to select a file on the hard disk. For this purpose, I'd like to use the standard Windows "open file" dialog. I seem to recall some method in VB 5 that sounded like OpenFileDialog or so, but can't find anythin...
  3. Excel VBA Dialog sheets
    Hi all, I need to switch between workbooks copying info from one dialog sheet in a workbook to a cell in another workbook. I have opened the page I need I have tried using the following and I guess I just don't understand the workbooks property properly. (new to VBA progr...
  4. Protecting all sheets and cells using VBA
    I'd like to for EVERY Sheet apart from the CURRENT SHEET 1. Select all the cells 2. Set Format Cells-->Protection--> Locked and Hidden = True 3. Do Tools-->Protection-->Protect Sheet and have a password entered (I'd like the password to be the same for e...
  5. Pointer: Will VBA in Excel do this?
    http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21566859.html I asked this question in Javascript, and it was suggested that vba in excel may suit my purposes better. :o) Bartender_1

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: DanRollinsPosted on 2009-09-20 at 02:47:06ID: 25376467

Here's how to do it in C++

It shouldn't bee too hard to translate that to VBA... it will use the same sort of techniques as in your existing code.

void CD05Dlg::OnBnClickedButton1()
{
	ULONG n;
	PIDLIST_ABSOLUTE pidlRoot;
 
	HRESULT hR= SHParseDisplayName( 
		L"C:\\Officesolutions\\MyFiles",
	    0, &pidlRoot, 0, &n
	);
	BROWSEINFO rBI= {0};
	rBI.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI | BIF_NONEWFOLDERBUTTON;
	rBI.pidlRoot= pidlRoot;
 
	LPITEMIDLIST pidl= SHBrowseForFolder( &rBI ); 
 
	TCHAR szPath[MAX_PATH];
	BOOL fRet= SHGetPathFromIDList( pidl, szPath );
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: WordSpecialistenPosted on 2009-09-20 at 23:05:29ID: 25380535

Thank you very much - but it does not help me. I am not able to re-write your c++ example to VBA. No matter what I do, it get syntax errors and compile erros.

 

by: DanRollinsPosted on 2009-09-21 at 17:01:09ID: 25388770

>>of my own choice as default root folder

Are you sure you meen "root" or do you mean default?  There is a significant difference.  You might read this C++ article (with pictures!) and let me know.  

http://www.experts-exchange.com/articles/Programming/System/Windows__Programming/Browse-for-Folder-Advanced-Options.html

I can probably translate to VBA, but I want to make sure that I'm heading toward the target goal.  

 

by: WordSpecialistenPosted on 2009-09-21 at 23:05:23ID: 25389921

Hello Dan,
Thank you for replying to me again. I can see what you mean and the difference. Sorry, I am Danish, so it is sometimes a challenge to find the right phrases in English. I have viewed the article, and there is no doubt: I want to pre-set an initial folder - a default folder - as shown in the first screendump in the article. So that the user does not have to browse 3-5 levels down in a network folder to get to the right main folder - All Departments - on the server.
I you can translate such a code example to VBA, I would be very grateful, and I have increased the points to 500.

 

by: DanRollinsPosted on 2009-09-22 at 00:06:38ID: 25390217

I really can't translate (the AddressOf thing is non-standard for VBA, but normal and easy in C++), but I found some code and played around with it until it seemed to  work (I tried it in an MsWord macro)

I just hard-coded an example pathname... strStartFolder you should be able to pass it in as a parameter

Original source was pieced together from various posts here:
http://www.vbcode.com/Asp/showsn.asp?theID=8207
and here:
http://www.bigresource.com/VB--SHBrowseForFolder-API-Question-deCCgLT4UJ.html</P>

 Declare Function SHBrowseForFolder Lib "shell32.dll" (lpbi As BrowseInfo) As Long
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal HWND As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" (ByVal pidList As Long, ByVal lpBuffer As String) As Long
 
Private Const WM_USER = &H400
Private Const BFFM_INITIALIZED = 1
Private Const BFFM_SELCHANGED = 2
Private Const BFFM_SETSTATUSTEXT = (WM_USER + 100)
Private Const BFFM_SETSELECTION = (WM_USER + 102)
Private Const BIF_RETURNONLYFSDIRS As Long = &H1
Private Const BIF_NEWDIALOGSTYLE As Long = &H40
Private Const BIF_STATUSTEXT As Long = &H4
Private Const cintMaxPath As Integer = 260
Private strStartFolder As String
Private strMStartFolder As String
 
Private Type BrowseInfo
  hWndOwner      As Long
  pIDLRoot       As Long
  pszDisplayName As Long
  lpszTitle      As Long
  ulFlags        As Long
  lpfnCallback   As Long
  lParam         As Long
  iImage         As Long
End Type
 
 Private Function GetAddressofFunction(add As Long) As Long
  GetAddressofFunction = add
End Function
  
Public Function GetFolderPath(ByVal strPath As String) As String
'Opens a Browse Folders Dialog Box
Dim lpIDList As Long
Dim tBrowseInfo As BrowseInfo
 
strStartFolder = "C:\temp\myprojects"
 
With tBrowseInfo
   .ulFlags = BIF_RETURNONLYFSDIRS + BIF_STATUSTEXT + BIF_NEWDIALOGSTYLE
End With
If strStartFolder <> "" Then
    strMStartFolder = strStartFolder & vbNullChar
    tBrowseInfo.lpfnCallback = GetAddressofFunction(AddressOf BrowseCallbackProc) 'get address of function.
End If
lpIDList = SHBrowseForFolder(tBrowseInfo)
 
GetFolderPath = strPath
End Function
 
 
Function BrowseCallbackProc(ByVal HWND As Long, ByVal uMsg As Long, ByVal lp As Long, ByVal pData As Long) As Long
 
    On Error Resume Next
    Dim lpIDList As Long
    Dim ret As Long
    Dim sBuffer As String
    Select Case uMsg
        Case BFFM_INITIALIZED
            Call SendMessage(HWND, BFFM_SETSELECTION, 1, strMStartFolder)
        Case BFFM_SELCHANGED
            'sBuffer = Space(cintMaxPath)
            'ret = SHGetPathFromIDList(lp, sBuffer)
            'If ret = 1 Then
            '    Call SendMessage(HWND, BFFM_SETSTATUSTEXT, 0, sBuffer)
            'End If
    End Select
    BrowseCallbackProc = 0
End Function
 
 
Sub test()
GetFolderPath ()
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:

Select allOpen in new window

 

by: WordSpecialistenPosted on 2009-09-22 at 00:19:43ID: 31631771

Thank you very much, this solution works, I can change the path to what ever I want now and the dialog displays corret. Well, it turned out that it was not as easy as I expected, I see  :-). Thank you very much once again.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...