Saveas的function非常好。 与单元格的名称

我正在尝试使下面的代码工作,以保存某种格式的文件名。 我希望它保存在打开文件的文件夹中,文件会将其名称更改为新的月份名称。 我已经得到了大部分工作,如目录select和文件名,并保存,但是,如果已经有一个同名的文件,或者如果有人select否或取消它会给出一个错误。 我尝试了各种方法试图绕过它,但现在我无所适从。 我有两个代码,他们都应该做同样的事情,只是变化。

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 

我还添加了消息框,试着在testing过程中看看它正在做什么。 我也尝试了Getsaveasfilename为了给用户select他/她自己的文件名和可能的文件夹的选项。 文件位置将每年更改一次。

如果您正在覆盖现有的文件,当已经有一个同名的文件尝试下面。

 NewFilename = loc + "\" + Range("NewFileName").Value & ".xlsm" Application.DisplayAlerts = False ActiveWorkbook.SaveAs NewFilename, FileFormat:=52 Application.DisplayAlerts = True