vba 如何在使用相对路径之前引用文件夹?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21185411/
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 01:25:37  来源:igfitidea点击:

How to reference the Folder Before using Relative Path?

excelvbarelative-path

提问by user3206476

I created a macro to transform Excel sheets into csv files.

我创建了一个宏来将 Excel 工作表转换为 csv 文件。

The Excel file is in the folder "C:\Files\Excel". I want the csv files to be saved in "C:\Files\Csv".

Excel 文件位于文件夹“C:\Files\Excel”中。我希望将 csv 文件保存在“C:\Files\Csv”中。

Assuming I'm within the Excel folder, I have to go to the folder before ("C:\Files") then add the CSV.

假设我在 Excel 文件夹中,我必须先转到该文件夹​​(“C:\Files”),然后添加 CSV。

It has to be relative path, because there are several files in different folders.

它必须是相对路径,因为在不同的文件夹中有几个文件。

回答by Siddharth Rout

This is not an exact answer but it's very easy to take it from here. This code will give you the path of folder one level up. Simply add `Csv" to it.

这不是一个确切的答案,但很容易从这里得到它。此代码将为您提供上一级文件夹的路径。只需在其中添加“Csv”即可。

Sub Sample()
    Dim CurPath As String, NewPath As String
    Dim pos As Long

    '~~> Get the path where the current file resides
    CurPath = Left$(ThisWorkbook.Path, InStrRev(ThisWorkbook.Path, "\"))

    '~~> This check is requried so that we know that there is a folder
    '~~> one level up. This doesn't take into account network paths
    '~~> like \mycomputer\myfolder\ For this you will have to have a separate check.
    pos = InStr(1, CurPath, "\")
    pos = InStr(pos + 1, CurPath, "\")

    If pos > 0 Then
        '~~> This will give you folder one level up
        Debug.Print Left$(Left(CurPath, Len(CurPath) - 1), InStrRev(Left(CurPath, Len(CurPath) - 1), "\"))
    Else
        Debug.Print "You are already in the root foder"
    End If
End Sub