9

I have a Macro that gets sub folder data. However I also want something from the main folder.

I looked at How to get current working directory using vba? but need to change activeworkbook path:

Application.ActiveWorkbook.Path might be "c:\parent\subfolder"

I would want

"c:\parent\"

Using Excel 365 VBA

Community
  • 1
  • 1
indofraiser
  • 1,014
  • 3
  • 18
  • 50

4 Answers4

12

As the path may not be the current working directory you need to extract the path from the string.

Find the last \ and read all characters to the left:

ParentPath = Left$(Path, InStrRev(Path, "\"))

If you are working around the current directory ChDir ".." will jump you up one level, the new path can be returned by CurrDir.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
7

The most reliable way to do this is to use the Scripting.FileSystemObject. It has a method that will get the parent folder without trying to parse it:

With CreateObject("Scripting.FileSystemObject")
    Debug.Print .GetParentFolderName(Application.ActiveWorkbook.Path)
End With
Comintern
  • 21,855
  • 5
  • 33
  • 80
0
Dim WbDir As String
Dim OneLvlUpDir As String

'get current WorkBook directory
WbDir = Application.ActiveWorkbook.Path

'get directory one level up
ChDir WbDir
ChDir ".."

'print new working directory and save as string. Use as needed.
Debug.Print CurDir()
OneLvlUpDir = CurDir()
-1

I think you mean this solution:

Sub t()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
MsgBox "ThisWorkbook.Path = " & ThisWorkbook.Path & vbLf & _
"Path one folder down = " & fso.GetFolder(ThisWorkbook.Path & "\." & "NewFolder").Path
Set fso = Nothing
End Sub
David Buck
  • 3,752
  • 35
  • 31
  • 35