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

use*_*476 2 excel vba relative-path

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

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

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

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

Sid*_*out 5

这不是一个确切的答案,但很容易从这里得到它。此代码将为您提供上一级文件夹的路径。只需在其中添加“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
Run Code Online (Sandbox Code Playgroud)