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
To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -" To navigate through multiple levels of directory at once, specify the full directory path that you want to go to. For example, use, "cd /var/www" to go directly to the /www subdirectory of /var/.
cd path-to-directory : The command followed by a path allows you to change into a specified directory (such as a directory named documents ). cd .. (two dots). The .. means “the parent directory” of your current directory, so you can use cd .. to go back (or up) one directory.
Type cd \ into the prompt to go back to the directory. If you need to navigate from a location back to the main command prompt, this command takes you back immediately.
Root directory navigation: Type “cd/” to enter the root directory. Home directory navigation: we use the “cd~” or “cd” command to move into the home directory. Back one level: we use the “cd-” command to return back to the previous folder. Remember, there is space between cd and the specified path.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With