Question : VBA Error Handler when excel sheet does not exist

The block of code below imports specific worksheets from 3 different Excel files into one table.  

For instances where Year1.xlsx does not exit, an error message fires (Run-time error ‘1004’).  I’m looking for a way to implement an error handler that would operate to this effect:

If a particular Excel Sheet doesn’t exist (e.g. ‘Year2.xlsx’), then execute the code on the next Excel sheet listed in ‘myPath = Array…’  

If none of the sheets exist listed in ‘myPath = Array…’, then fire this code:
1:
MsgBox "Worksheets do not exist. Exiting sub now!", vbInformation, "Error"
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
Public Sub ImportExcelSheets()
Dim myPath(), j
myPath = Array("\\serverName\Year1.xlsx", "\\serverName\Year2.xlsx", "\\serverName\Year3.xlsx")
For j = LBound(myPath) To UBound(myPath)
    
    
Set objXL = CreateObject("Excel.Application")
    objXL.Workbooks.Open xlPath, , True
    With objXL
        For i = 1 To .Worksheets.Count
            If InStr(.Worksheets(i).Name, "widget") Then
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, _
             "tableName", myPath(j), True, .Worksheets(i).Name & "!A:M"
            End If
        Next
    End With
    objXL.Quit
    Set objXL = Nothing

Next

End Sub

Answer : VBA Error Handler when excel sheet does not exist

use this

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
Public Sub ImportExcelSheets()
Dim myPath(), j, iCnt as integer
myPath = Array("\\serverName\Year1.xlsx", "\\serverName\Year2.xlsx", "\\serverName\Year3.xlsx")
For j = LBound(myPath) To UBound(myPath)
    
if dir(mypath(j))<>"" then

Set objXL = CreateObject("Excel.Application")
    objXL.Workbooks.Open myPath(j), , True
    With objXL
        For i = 1 To .Worksheets.Count
            If InStr(.Worksheets(i).Name, "widget") Then
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, _
             "tableName", myPath(j), True, .Worksheets(i).Name & "!A:M"
            End If
        Next
    End With
    objXL.Quit
    Set objXL = Nothing

    else
    iCnt=iCnt + 1
end if
Next
if icnt=3 then
MsgBox "Worksheets do not exist. Exiting sub now!", vbInformation, "Error"
exit sub
end if 

End Sub
 
Toggle HighlightingOpen in New WindowSelect All
Random Solutions  
 
programming4us programming4us