【发布时间】:2017-05-24 02:56:04
【问题描述】:
我正在尝试在 excel 模板上设置自动保存功能,以免覆盖原始模板。
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”,类型不匹配
我做错了什么?
【问题讨论】:
-
在不知道你问题的背景的情况下,这可能是一个愚蠢的评论,但是......既然你在谈论一个 模板,你为什么不能将它保存为带有密码保护的模板 (*.xlt)(可能在文件系统中标记为只读)?
-
您在测试
If NameFile = False thenNameFile 是一个字符串时遇到此错误,它几乎不可能是True或False。我不相信这段代码无论如何都能做你想做的事。 Alan 的建议适合你吗? -
以上两个优点。您也可以在工作簿模块中放置一个 Workbook_Beforesave 过程,以防止它被覆盖。