Macro error handling when save path doesnt exist

2019-08-23 10:27发布

I use the following code to save backup versions to a couple different external backup locations and to the original file. Sometime though either of the external backup drives is not connected and generates an error.

How can I skip to the next line of code to execute the other two saves? I will also be adding a message box when this happens.

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

标签: excel vba
1条回答
我只想做你的唯一
2楼-- · 2019-08-23 11:17

You could use the following function

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

    On Error GoTo EH

    wkb.SaveCopyAs fName
    wkbSaveCopyAs = True

EH:

End Function

in your code like that

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
查看更多
登录 后发表回答