我正在尝试创建一个宏,让用户将工作簿的备份保存到特定位置。我在下面尝试了我的代码但得到了错误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
我尝试调整的事情
任何帮助都会很棒。
另存为打开的窗口
答案 0 :(得分:0)
GetSaveAsFilename
返回Variant
,如果用户取消了SaveAs对话框,则为布尔False
,如果未取消,则为包含他们选择的文件名的字符串对话框。
你的话说
Dim saveSuccess As Boolean
如果返回非布尔值,将导致问题。所以使用
Dim saveSuccess As Variant
代替。
但这仍然会给你带来其他问题:
Sheets(3).Range "E22" = Date
无效,可能是Sheets(3).Range("E22") = Date
*xlsm
应该是*.xlsm
您实际上没有保存文件。你最后的代码应该是这样的:
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