打开文件时的错误处理

时间:2014-02-17 22:21:04

标签: vba excel-vba excel-2010 excel

我有以下代码:

子补丁()

Dim r As Long, j As Long, c As Long
Dim day As Long, month As Long, year As Long


year = 2014

    For month = 2 To 2 Step -1

        For day = 12 To 1 Step -1

            On Error GoTo nextday
            Workbooks.Open ("G:\Manu\PVA\Pmo_Multiprogrammes\10-Process & Tools\00 GESTION DE CHANGEMENT\03 AMÉLIORER\20 Base de données\00 Mproduct\19-Suivi\Suivi du Cseries\rapport quotidien\Suivi Cseries_" & day & "_" & month & "_" & year & ".xlsm")
            On Error GoTo 0

            '## Do stuff

            Workbooks("Suivi Cseries_" & day & "_" & month & "_" & year & ".xlsm").Close (False)

nextday:
        Next 'day

    Next 'mont

End Sub

当找不到文件时我只想让cofe继续下一个文件,这就是为什么我把“One Error GoTo”放到第二天但是它不起作用。我仍然弹出未找到的文件,也会出现调试弹出窗口。必须有一些我不知道的东西。

1 个答案:

答案 0 :(得分:2)

使用此模式:

Sub patch()

    Dim r As Long, j As Long, c As Long
    Dim myDay As Long, myMonth As Long, myYear As Long
    Dim wb As Workbook

    Application.DisplayAlerts = False       

    myYear = 2014

    For myMonth = 2 To 2 Step -1    
        For myDay = 12 To 1 Step -1

            On Error Resume Next
            Set wb = Workbooks.Open("G:\Manu\PVA\Pmo_Multiprogrammes\10-Process & Tools\00 GESTION DE CHANGEMENT\03 AMÉLIORER\20 Base de données\00 Mproduct\19-Suivi\Suivi du Cseries\rapport quotidien\Suivi Cseries_" & myDay & "_" & myMonth & "_" & myYear & ".xlsm")
            On Error GoTo 0

            If Not wb Is Nothing Then
                '## Do stuff
                wb.Close False
            End If
        Next 'day
    Next 'mont

    Application.DisplayAlerts = True
End Sub

BTW ,不要使用具有特定名称的变量,例如daymonthyear sicne,在这种情况下,VBA函数具有此名称({ {1}},DAY()MONTH())无效