Excel VBA文件保存

我正在尝试在Excel模板上设置自动保存function,以便原始模板不会被覆盖。

Dim NameFile As String 'Gets the users username UserName = Environ$("UserName") 'User is to input data type datat= Application.InputBox("Enter a Data Type", "Data Type") With Worksheets("Home") 'Sets up auto filename with YearMonthDay - Username - Filename(From a specific Cell) - Data Type NameFile = Format(Date, "yyyymmd") & " - " & UserName & " - " & Range("A1") & " - " & datat & ".xlsm" End With 'Sets up save location NameFile = Application.GetSaveAsFilename(InitialFileName:=Environ("USERPROFILE") & "\Desktop\" & NameFile, Filefilter:=" Excel (*.xlsm), *.xlsm") If NameFile = False Then 'Tell user with a caution that the file has not been saved MsgBox "File not saved", vbCritical, "Caution" Exit Sub Else ThisWorkbook.SaveAs Filename:=NameFile MsgBox "File Saved" End If 

当我不保存该文件,并单击取消我得到消息框告诉我,该文件没有保存…这是我想要的。

但是当我用给定的名字保存文件时,我得到一个运行时错误“13”,types不匹配

我究竟做错了什么?

你应该昏暗的 NameFile作为变种

这样它可以保存一个布尔值或一个string