【问题标题】:Excel VBA File saveExcel VBA 文件保存
【发布时间】: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 then NameFile 是一个字符串时遇到此错误,它几乎不可能是True 或False。我不相信这段代码无论如何都能做你想做的事。 Alan 的建议适合你吗?
  • 以上两个优点。您也可以在工作簿模块中放置一个 Workbook_Beforesave 过程,以防止它被覆盖。

标签: excel vba


【解决方案1】:

您应该 Dim NameFile 为 Variant

这样它可以保存 Boolean 或 String。

【讨论】:

  • 谢谢你的朋友,我什至没有考虑过变体。这很完美。再次感谢您
  • @S.Smith 非常欢迎您...感谢您的反馈!
猜你喜欢
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 2020-06-03
相关资源
最近更新 更多