如何通过网络复制文件时处理错误

时间:2017-10-20 16:35:05

标签: vba ms-access access-vba

我正在从旧数据库中回收代码。

对于位于全国各地的一个人,我相信可能存在一些连接问题。

Public Function BackUpBackend()

    Dim Source As String
    Dim Target As String
    Dim retval As Integer

    Source = "\\network\backend\accessfile.accdb"

    Target = "\\network\backend\backup\"
    Target = Target & Format(Date, "mm-dd") & "@"
    Target = Target & Format(Time, "hh-mm") & ".accdb"

    retval = 0
    Dim objFSO As Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    retval = objFSO.CopyFile(Source, Target, True)
    Set objFSO = Nothing

End Function

有没有办法检测此代码中的连接错误?如果有,可以重新建立连接,或者在问题出现时一起停止备份过程吗?

1 个答案:

答案 0 :(得分:2)

在VBA中你可以做到

On Error Resume Next

将继续过去的错误。这可能很危险,因此通常最好尽快再次启用错误处理

On Error Goto 0

您可以为要执行特定操作的错误定义自定义处理程序: 来自VBA Reference

Sub InitializeMatrix(Var1, Var2, Var3, Var4)
   On Error GoTo ErrorHandler
   . . .
   Exit Sub
ErrorHandler:
   . . .
   Resume Next
End Sub

所以你可以这样做:(我还没有测试过)

Public Function BackUpBackend()

    Dim Source As String
    Dim Target As String
    Dim retval As Integer


    Source = "\\network\backend\accessfile.accdb"

    Target = "\\network\backend\backup\"
    Target = Target & Format(Date, "mm-dd") & "@"
    Target = Target & Format(Time, "hh-mm") & ".accdb"

    retval = 0
    Dim objFSO As Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    On Error Goto ErrorHandler
    retval = objFSO.CopyFile(Source, Target, True)
    Set objFSO = Nothing
    On Error Goto 0

    Exit Function

ErrorHandler:
    MsgBox("Backup failed. If this happens often contact IT", vbExclamation )

End Function