I have a folder with about 75 Excel files (.xlsx). The Excel files should all have five named worksheets (for example: SurveyData
, AmphibianSurveyObservationData
, BirdSurveyObservationData
, PlantObservationData
, and WildSpeciesObservationData
). Unfortunately, sometimes the Excel files have only a subset of the worksheets (i.e., One Excel file might have all five worksheets, while another would only have the SurveyData
and AmphibianSurveyObservationData
worksheets).
I would like to import all these Excel files into Access and have information from each worksheet put into a separate table. For example, I want all the data from the SurveyData
worksheet in all the Excel files to be put into an Access Table called SurveyData
. I found this VBA code (see below) and it seems to work fine when all the worksheets are present in the Excel file, but when one worksheet is missing, the script stops and doesn't continue importing any of the other files. Is there any way to only import a worksheet if it's present in the Excel file, otherwise just skip over the import?
Function ImportExcelFiles()
Dim strFile As String
DoCmd.SetWarnings False
' Set file directory for files to be imported
strPath = "D:\SpeciesData\MoELoadform\2015SpeciesDetectionLoadforms - Copy\"
' Tell it to import all Excel files from the file directory
strFile = Dir(strPath & "*.xls*")
' Start loop
Do While strFile <> ""
' Import file
DoCmd.TransferSpreadsheet transfertype:=acImport, tablename:="SurveyData", FileName:=strPath & strFile, HasFieldNames:=True, Range:="SurveyData!A1:AD"
DoCmd.TransferSpreadsheet transfertype:=acImport, tablename:="AmphibianSurveyObservationData", FileName:=strPath & strFile, HasFieldNames:=True, Range:="AmphibianSurveyObservationData!A1:AQ"
DoCmd.TransferSpreadsheet transfertype:=acImport, tablename:="BirdSurveyObservationData", FileName:=strPath & strFile, HasFieldNames:=True, Range:="BirdSurveyObservationData!A1:AQ"
DoCmd.TransferSpreadsheet transfertype:=acImport, tablename:="PlantObservationData", FileName:=strPath & strFile, HasFieldNames:=True, Range:="PlantObservationData!A1:BS"
DoCmd.TransferSpreadsheet transfertype:=acImport, tablename:="WildSpeciesObservationData", FileName:=strPath & strFile, HasFieldNames:=True, Range:="WildSpeciesObservationData!A1:AP"
' Loop to next file in directory
strFile = Dir
Loop
MsgBox "All data has been imported.", vbOKOnly
End Function