VBA数组错误

我有下面的代码,它使用两个for循环(Prod和Dev)
数组中有很多值,但是我只用了两个例子,它将数值从一个excel复制到另一个。

现在,有一个文件NSA_103_B_Roles.xls文件不存在的可能性在这种情况下,我不希望代码采取任何行动,所以我已经把on error resume next

但还是在不存在的excel中打印价值,原因是什么?

 Private Sub CommandButton1_Click() Prod = Array("ZS7_656", "PCO_656") Dev = Array("NSA_103", "DCA_656") For lngCounter1 = LBound(Dev) To UBound(Dev) For lngCounter = LBound(Prod) To UBound(Prod) On Error Resume Next Set Zz2 = Workbooks.Open("C:\Users\*****\Desktop\New folder\" & Dev(lngCounter1) & "_B_Roles.xls") Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value = "anirudh" ThisWorkbook.Sheets(Prod(lngCounter)).Range("A2").Value = Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value On Error GoTo 0 Next lngCounter Next lngCounter1 End Sub 

尝试下面的代码,在代码的评论里面的解释:

 Private Sub CommandButton1_Click() Dim Zz2 As Workbook Prod = Array("ZS7_656", "PCO_656") Dev = Array("NSA_103", "DCA_656") For lngCounter1 = LBound(Dev) To UBound(Dev) For lngCounter = LBound(Prod) To UBound(Prod) ' ==== this section starts the error handling === On Error Resume Next Set Zz2 = Workbooks.Open("C:\Users\*****\Desktop\New folder\" & _ Dev(lngCounter1) & "_B_Roles.xls") On Error GoTo 0 If Zz2 Is Nothing Then ' <-- unable to find the file MsgBox "unable to find the specified file", vbCritical Exit Sub End If ' === Up to Here === Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value = "anirudh" ThisWorkbook.Sheets(Prod(lngCounter)).Range("A2").Value = Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value Next lngCounter Next lngCounter1 End Sub