2014-01-17 41 views
2

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

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

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

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

+0

请分享你怎么'transforming' Excel表到CSV? –

+0

你的意思是CSV文件夹是在同一文件夹中的Excel文件夹位于何处? –

+0

我的代码有几个想法:检查文件夹是否存在 - 如果没有,创建它。检查Dir命令或FileSystemObject的帮助或教程,然后在保存而不是旧的时候使用新路径。发现问题是否卡住 –

回答

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 
+0

如何将此代码适配到SharePoint文件夹? –