I have to import one excel file that contain multiple worksheets into an access table by vba, but my current code listed below will only copy the first worksheet record of the excel and import into an access table, all the worksheets got same format and layout. how to enable my code to copy all the worksheets' records and import into a table in access. Please feel free to answer the question and thanks for any answer.
Private Sub Command9_Click()
' Requires reference to Microsoft Office 11.0 Object Library.
Dim fDialog As FileDialog
Dim varFile As Variant
' Clear listbox contents.
'Me.FileList.RowSource = ""
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Filters.Add "Excel File", "*.xls"
.Filters.Add "Excel File", "*.xlsx"
If .Show = True Then
'Loop through each file selected and add it to our list box.
For Each varFile In .SelectedItems
' Label3.Caption = varFile
Const acImport = 0
Const acSpreadsheetTypeExcel9 = 8
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
"Plymouth - Nominal Detail", varFile, True
Next
MsgBox ("Import data successful!")
End If
End With
End Sub
You need to specify the sheets, for example:
Private Sub Command9_Click()
' Requires reference to Microsoft Office 11.0 Object Library.
Dim fDialog As FileDialog
Dim varFile As Variant
' Clear listbox contents.
'Me.FileList.RowSource = ""
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Filters.Add "Excel File", "*.xls"
.Filters.Add "Excel File", "*.xlsx"
If .Show = True Then
'Loop through each file selected and add it to our list box.
For Each varFile In .SelectedItems
' Label3.Caption = varFile
Const acImport = 0
Const acSpreadsheetTypeExcel9 = 8
''This gets the sheets to new tables
GetSheets varFile
Next
MsgBox ("Import data successful!")
End If
End With
End Sub
Sub GetSheets(strFileName)
'Requires reference to the Microsoft Excel x.x Object Library
Dim objXL As New Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Object
'objXL.Visible = True
Set wkb = objXL.Workbooks.Open(strFileName)
For Each wks In wkb.Worksheets
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
wks.Name, strFileName, True, wks.Name & "$"
Next
'Tidy up
wkb.Close
Set wkb = Nothing
objXL.Quit
Set objXL = Nothing
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With