Excel宏 - 相对路径 - 文件夹之前

时间:2014-01-17 11:57:11

标签: vba excel-vba path relative excel

我正在创建一个宏来将Excel工作表转换为csv文件。它基本上工作,但我希望它将生成的csv文件保存到不同的文件夹。

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

因此,假设我在Excel文件夹中,我必须在(C:\Files)之前转到该文件夹​​,然后添加CSV。但它必须是相对路径,因为在不同的文件夹中有几个文件。

关于如何使用相对路径的任何想法?

1 个答案:

答案 0 :(得分:4)

这不是一个确切的答案,但从这里开始很容易。此代码将为您提供一级文件夹的路径。只需添加`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