使用来自单元格的路径来保存Excel文件的VBA宏

时间:2014-01-07 18:17:24

标签: excel vba excel-vba

我尝试使用硬线和单元格值的组合来保存文件以确定文件路径。

在单元格A29中,我有一个公式输出:

  

2014 \ 1月\ High Cash 1.7.14

我收到预期:声明结束错误。

代码是:

ActiveWorkbook.SaveAs Filename:="S:\IRD\Tamarac\Daily High Cash Reporting\& Range("A29").Text & ".xlsx", FileFormat:= _  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _ , CreateBackup:=False

2 个答案:

答案 0 :(得分:5)

建议您更进一步,确保过滤掉任何无效的文件名字符(例如保存错误)

此代码将删除

  

[] /:*?“<>

主要代码

Sub CleanSave()
Dim fileName As String
fileName = "C:\temp\" & strClean(Range("A29").Value) & ".xlsx"
ActiveWorkbook.SaveAs fileName:=fileName, FileFormat:=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

清洁功能

Function strClean(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "[\[\]|\/\\:\*\?""<>]"
    .Global = True
    strClean = .Replace(strIn, vbNullString)
End With
End Function

答案 1 :(得分:4)

我会重写如下:

Dim fileName As String
fileName = "S:\IRD\Tamarac\Daily High Cash Reporting\" & Range("A29").Text & ".xlsx"
ActiveWorkbook.SaveAs Filename:=fileName, FileFormat:=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False

我认为你所缺少的是代码中“报告”部分之后的结束双引号......