【发布时间】:2020-10-31 08:05:14
【问题描述】:
我有一个获取子文件夹数据的宏。但是我也想要主文件夹中的一些东西。
我查看了How to get current working directory using vba?,但需要更改活动工作簿路径:
Application.ActiveWorkbook.Path might be "c:\parent\subfolder"
我想要
"c:\parent\"
使用 Excel 365 VBA
【问题讨论】:
我有一个获取子文件夹数据的宏。但是我也想要主文件夹中的一些东西。
我查看了How to get current working directory using vba?,但需要更改活动工作簿路径:
Application.ActiveWorkbook.Path might be "c:\parent\subfolder"
我想要
"c:\parent\"
使用 Excel 365 VBA
【问题讨论】:
由于路径可能不是当前工作目录,您需要从字符串中提取路径。
找到最后一个\ 并读取左侧的所有字符:
ParentPath = Left$(Path, InStrRev(Path, "\"))
如果你在当前目录下工作,ChDir ".." 会让你上一级,CurrDir 可以返回新路径。
【讨论】:
最可靠的方法是使用 Scripting.FileSystemObject。它有一个方法可以在不尝试解析的情况下获取父文件夹:
With CreateObject("Scripting.FileSystemObject")
Debug.Print .GetParentFolderName(Application.ActiveWorkbook.Path)
End With
【讨论】:
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()
【讨论】:
我认为你的意思是这个解决方案:
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
【讨论】: