vba 上一级文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39637185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:19:20  来源:igfitidea点击:

Go up one folder level

excelvbaexcel-vba

提问by indofraiser

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:

我查看了如何使用 vba 获取当前工作目录?但需要更改活动工作簿路径:

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

I would want

我想要

"c:\parent\"

Using Excel 365 VBA

使用 Excel 365 VBA

回答by Alex K.

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.

如果您在当前目录周围工作,ChDir ".."则会将您跳转到一个级别,新路径可以通过CurrDir.

回答by Comintern

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:

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

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