
I ran into a problem, and maybe some of you out there have as well: Ever have an Excel file open and need to open the folder it's in?
Here's how it happens: After I browse to a folder and open the workbook I want, I close the Explorer window. It's a bad habit, but I can't help it. Inevitably, I need to open another file in the same folder. So I have to browse the entire folder tree again to get back to the folder I was in. No more!
This code will open Windows Explorer to the folder where the current file is located. The "Declare" statement should be placed at the top of a standard module. Note that it works on saved workbooks only. It uses a Windows API to open Windows Explorer.
Declare Function ShellExecute Lib "shell32.dll" Alias _
"ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation _
As String, ByVal lpFile As String, ByVal lpParameters _
As String, ByVal lpDirectory As String, ByVal nShowCmd _
As Long) As Long
Sub OpenContainingFolder() On Error GoTo ErrorHandler Dim currentWkbkPath As String currentWkbkPath = ActiveWorkbook.Path ShellExecute 0, "open", currentWkbkPath, 0, 0, 1 ProgramExit: Exit Sub ErrorHandler: MsgBox Err.Number & " - " & Err.Description Resume ProgramExit End Sub
Usable in other Office programs too! For example, MS Word:
Sub OpenContainingFolder() On Error GoTo ErrorHandler Dim currentDocPath As String currentDocPath = ActiveDocument.Path ShellExecute 0, "open", currentDocPath, 0, 0, 1 ProgramExit: Exit Sub ErrorHandler: MsgBox Err.Number & " - " & Err.Description Resume ProgramExit End Sub
and MS Access:
Sub OpenContainingFolder() On Error GoTo ErrorHandler Dim currentDBPath As String currentDBPath = Application.CurrentProject.Path ShellExecute 0, "open", currentDBPath, 0, 0, 1 ProgramExit: Exit Sub ErrorHandler: MsgBox Err.Number & " - " & Err.Description Resume ProgramExit End Sub
although the Access VBA code must be tied to a specific DB. Now go, and never have this problem again!
Thanks JP!
This will be a big time saver for me.
If I understand what your code is doing correctly, then (for Excel) I think this one-liner will do the same thing…
Sub OpenContainingFolder() Application.Dialogs(xlDialogOpen).Show ActiveWorkbook.Path End SubRick, that's true but JP's solution opens the folder with Windows Explorer instead of the Excel Open File dialog.
@Reuvain,
Ah, yes, okay, in that case, what about this one-liner instead then…
Sub OpenContainingFolder() Shell "explorer.exe " & ActiveWorkbook.Path & "\", vbNormalFocus End SubSorry to be asking a basic question, but if i want this Macro to be available for ALL of the excel files that I open, where (which file) should this code be put in? Is there a global file in which this can be put, which will automatically load/execute this code?
Put the code in a module in your Personal.xls file.
If you are not familiar with a Personal.xls file then see the link below.
http://www.rondebruin.nl/personal.htm