10

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

4 Answers 4

13

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.

3
  • I should say it will always be in the working directory (in this case!). But good to know! Commented Sep 22, 2016 at 11:07
  • Try it like this: Left$(application.ActiveWorkbook.Path, InStrRev(application.ActiveWorkbook.Path, "\")-1)
    – Vityata
    Commented Sep 22, 2016 at 11:09
  • Thanks. Spotted I'd put the code a line to early as well! (On the main code) Commented Sep 22, 2016 at 11:15
8

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
1
  • This gives you the subfolder, not the parent folder.
    – TJJ
    Commented Aug 2, 2022 at 12:47
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.