保存路径不存在时的宏错误处理

时间:2019-03-30 07:28:35

标签: excel vba

我使用以下代码将备份版本保存到几个不同的外部备份位置以及原始文件中。有时尽管两个外部备份驱动器中的任何一个都未连接并产生错误。

如何跳到下一行代码以执行其他两次保存?发生这种情况时,我还将添加一个消息框。

Sub SaveToLocations()
' Saves active file to current plus two other backup locations, appends date and time in front of file name

    Dim datim As String
    datim = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss_")

    ActiveWorkbook.SaveCopyAs "I:\FBackupCS\" & datim & ActiveWorkbook.Name
    ActiveWorkbook.SaveCopyAs "E:\CS Docs\FBackupCS\" & datim & ActiveWorkbook.Name
    ActiveWorkbook.Save
End Sub

1 个答案:

答案 0 :(得分:0)

您可以使用以下功能

Function wkbSaveCopyAs(ByVal wkb As Workbook, ByVal fName As String) As Boolean

    On Error GoTo EH

    wkb.SaveCopyAs fName
    wkbSaveCopyAs = True

EH:

End Function

在这样的代码中

Sub SaveToLocations()
' Saves active file to current plus two other backup locations, appends date and time in front of file name

    Dim datim As String
    datim = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss_")

    'ActiveWorkbook.SaveCopyAs "I:\FBackupCS\" & datim & ActiveWorkbook.Name
    If Not wkbSaveCopyAs(ActiveWorkbook, "I:\FBackupCS\" & datim & ActiveWorkbook.Name) Then
        MsgBox "Ups, not saved", vbOKOnly
    End If

    'ActiveWorkbook.SaveCopyAs "E:\CS Docs\FBackupCS\" & datim & ActiveWorkbook.Name
    If Not wkbSaveCopyAs(ActiveWorkbook, "E:\CS Docs\FBackupCS\" & datim & ActiveWorkbook.Name) Then
        MsgBox "Ups, not saved", vbOKOnly
    End If

    ActiveWorkbook.Save
End Sub