VBA excel Application.getsaveasfilename错误13

时间:2017-07-05 19:59:27

标签: excel vba excel-vba

我正在尝试创建一个宏,让用户将工作簿的备份保存到特定位置。我在下面尝试了我的代码但得到了错误13消息。我不需要将它保存为支持宏的工作簿,但我认为这会更容易。

Sub openSaveDialog()
'
' gives error 13 message when clicking save
'
Dim saveSuccess As Boolean
Dim fNameRec As String
Dim dateNow As String
Dim saveToDir As String
saveToDir = "Z:\location of save\Old Archive spreadsheets\"
dateNow = Format(Now(), "mmddyyyy")
fNameRec = saveToDir & "BinderArchiveBackup_" & dateNow
Sheets(3).Range("E25") = fNameRec
'check if backed up today
If (Sheets(3).Range("E22") = Date) Then
    MsgBox "backup already saved today no need to save again"
    Exit Sub
End If

'open save as window
saveSuccess = Application.GetSaveAsFilename(InitialFileName:=fNameRec, FileFilter:= _
"Excel Files (*.xlsx)," & "*.xlsx, Macro Enabled" & _
"Workbook (*.xlsm), *xlsm")
'if backup saved, update date of last backup
If saveSuccess Then
    Sheets(3).Range "E22" = Date
    MsgBox "save successful"
End If
'if backup not saved, inform user
If Not saveSuccess Then
    MsgBox "save canceled, please save backup before adding new items to the archive today"
End If
End Sub

我尝试调整的事情

  • 文件过滤器只启用宏
  • 文件过滤器只是excel工作簿
  • 空白文件过滤器保存为所有文件类型
  • 名称末尾带有.xlsx的空白文件过滤器
  • 没有目录但使用ChDir的初始文件名,因此无论如何它都会在正确的保存位置打开

任何帮助都会很棒。

另存为打开的窗口

[1]

1 个答案:

答案 0 :(得分:0)

GetSaveAsFilename返回Variant,如果用户取消了SaveAs对话框,则为布尔False,如果未取消,则为包含他们选择的文件名的字符串对话框。

你的话说

Dim saveSuccess As Boolean
如果返回非布尔值,

将导致问题。所以使用

Dim saveSuccess As Variant

代替。

但这仍然会给你带来其他问题:

  1. Sheets(3).Range "E22" = Date无效,可能是Sheets(3).Range("E22") = Date
  2. *xlsm应该是*.xlsm
  3. 您实际上没有保存文件。你最后的代码应该是这样的:

    If saveSuccess = False Then
        'if backup not saved, inform user
        MsgBox "save canceled, please save backup before adding new items to the archive today"
    Else
        If UCase(Right(saveSuccess, 5)) = ".XLSM" Then
            ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbookMacroEnabled
            'if backup saved, update date of last backup
            Sheets(3).Range("E22") = Date
            MsgBox "save successful"
        ElseIf UCase(Right(saveSuccess, 5)) = ".XLSX" Then
            ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbook
            'if backup saved, update date of last backup
            Sheets(3).Range("E22") = Date
            MsgBox "save successful"
        Else
            MsgBox "Unrecognised file extension chosen - backup not created"
        End If
    End If