上一个文件夹级别

时间:2016-09-22 11:00:12

标签: excel vba excel-vba

我有一个获取子文件夹数据的宏。但是我也想从主文件夹中找到一些东西。

我查看How to get current working directory using vba?但需要更改activeworkbook路径:

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

我想要

"c:\parent\"

使用Excel 365 VBA

4 个答案:

答案 0 :(得分:6)

由于路径可能不是当前工作目录,因此需要从字符串中提取路径。

找到最后一个\并读取左侧的所有字符:

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

如果您正在使用当前目录ChDir ".."将向上跳过一个级别,则CurrDir可以返回新路径。

答案 1 :(得分:4)

最可靠的方法是使用Scripting.FileSystemObject。它有一个方法可以获取父文件夹而不试图解析它:

With CreateObject("Scripting.FileSystemObject")
    Debug.Print .GetParentFolderName(Application.ActiveWorkbook.Path)
End With

答案 2 :(得分: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()

答案 3 :(得分:-1)

我想你是说这个解决方案:

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