excel vba saveasui文件path

我已经创build了一个注册变更的模板。 这些是在这个过程中的要求和进一步的pipe理。 我有一个代码在这个模板来保存文件作为一个Excelmacros启用工作簿,总是。 这个代码的问题是,我不能定义一个特定的文件夹来保存文件。 在所有情况下,popup“另存为”对话框,用户必须能够定义他们自己的文件名。 我想为所有用户定义path。 有没有人知道如何在这个macros中添加一个文件位置(path),以使其工作?

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim FileNameVal As String If SaveAsUI Then FileNameVal = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") Cancel = True If FileNameVal = "False" Then 'User pressed cancel Exit Sub End If Application.EnableEvents = False If Right(ThisWorkbook.Name, 5) <> ".xlsm" Then ThisWorkbook.SaveAs Filename:=FileNameVal, FileFormat:=xlOpenXMLWorkbookMacroEnabled Else ThisWorkbook.SaveAs Filename:=FileNameVal, FileFormat:=xlOpenXMLWorkbookMacroEnabled End If Application.EnableEvents = True End If End Sub 

提前致谢。

亲切的问候,Remco H.

如果你想生成一个唯一的文件名,你可以使用类似下面的函数:

 Function NextFileName(basename As String) As String Dim followup As Integer Dim pathname As String pathname = "C:\Temp\Temp\" ' Include the trailing path separator so that we don't have to do it later followup = 1 Do NextFileName = pathname & basename & "-" & followup & ".xlsm" If Dir(NextFileName) = "" Then Exit Function followup = followup + 1 Loop End Function 

然后你可以从你的主代码中调用它

 Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim FileNameVal As String If SaveAsUI Then ' <-- Exclude the IF statement if you want EVERY save to have a new follow up number ' rather than just "Save As" saves Application.EnableEvents = False 'Generate the filename FileNameVal = NextFileName(Format(Now, "yymmdd")) ThisWorkbook.SaveAs Filename:=FileNameVal, FileFormat:=xlOpenXMLWorkbookMacroEnabled 'Maybe advise the user that the save has happened, and where it went to MsgBox "Spreadsheet saved as " & FileNameVal Cancel = True Application.EnableEvents = True End If End Sub