我正在尝试使以下代码用于以特定格式保存文件名。我希望它保存在文件打开的文件夹中。该文件将其名称更改为新的月份名称。我已经完成了大部分工作,例如目录选择和文件名,并且要保存,但是,如果已经存在具有相同名称的文件,或者有人选择否或取消它会产生错误。我尝试了各种尝试绕过它的方法,但现在我不知所措。我有两个代码,他们都应该做同样的事情,只是变化。
Sub saving1()
' Saves the file under a new name based on the new month date.
Dim NewFilename As String
Dim tempnm
Dim loc ' variable for file location
loc = Application.ThisWorkbook.Path 'loads the file location on the loc variable
MsgBox loc
' creates the file name for saving includes the current path.
NewFilename = loc + "\" + Range("NewFileName").Value & ".xlsm"
'tempmm = Application.GetSaveAsFilename initialfilename
ActiveWorkbook.SaveAs NewFilename, FileFormat:=52
'Application.DisplayAlert = False
'On Error Resume Next 'to omit error when cancel is pressed
' MsgBox "Not saved"
'ActiveWorkbook.Save
'If Err.Number <> 1004 Then 'optional, to confirmed that is not saved
' MsgBox "Not saved"
'End If
' On Error GoTo 0 'to return standard error operation
End Sub
Sub saving()
' Saves the file under a new name based on the new month date.
Dim NewFilename As String
Dim loc ' variable for file location
loc = Application.ThisWorkbook.Path 'loads the file location on the loc variable
' creates the file name for saving includes the current path.
NewFilename = loc + "\" + Range("NewFileName").Value & ".xlsm"
ActiveWorkbook.SaveAs NewFilename, FileFormat:=52
End Sub
我还添加了消息框,以便在测试期间查看它正在做什么。我还尝试了Getsaveasfilename,以便为用户提供选择他/她自己的文件名和可能的文件夹的选项。文件位置每年更改一次。
答案 0 :(得分:1)
如果你正在考虑覆盖现有文件,当下面已经有一个同名文件时,请尝试下面。
NewFilename = loc + "\" + Range("NewFileName").Value & ".xlsm"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs NewFilename, FileFormat:=52
Application.DisplayAlerts = True