I will show you two methods for this. The first methods only retrieves
data from one Excel sheet to one Access table. The second method uses
array so that you can retrieve data from multiple Excel Sheets and
populate multiple Access tables.
----------------------------------------------------
'--method 1 -- one Excel Sheet to one Access Table
Sub GetDataFromExcel()
Dim dbsTemp As Database
Dim tdfLinked As TableDef
Set dbsTemp = CurrentDb
Set tdfLinked = dbsTemp.CreateTableDef("tblSheet1")
tdfLinked.Connect = _
"Excel 5.0;HDR=YES;IMEX=2;DATABASE=C:\Dir1\Book1.xls"
tdfLinked.SourceTableName = "Sheet1$"
dbsTemp.TableDefs.Append tdfLinked
DoCmd.RunSql "Select * Into tbl1 From tblSheet1"
End Sub
----------------------------------------------------
Basically you are connecting to a respective Excel sheet using the
connection string here (replace C:\Dir1\Book1.xls with the actual path
to your Excel Workbook). Oh, and HDR=YES means the first row in the
Excel sheet is a header row.
"Excel 5.0;HDR=YES;IMEX=2;DATABASE=C:\Dir1\Book1.xls"
This same connection string works with Excel97 or Excel2000 or
Excel2002. Note: when you reference your Excel Sheet name ("Sheet1" in
my example) you have to append a $ sign to it. The actual sheet name is
"Sheet1" (or whatever your sheet name is). You append the $ and in the
code above (and below) you are now referencing "Sheet1$". Once you
have connected to your Excel sheet you can use a simple Select * Into...
statement to retrieve the Excel data from your connected Excel table
into a native Access table.
In method 2 I am using an array of Excel Sheets and 2 arrays of Access
tables. Then I loop through the arrays to get data from multiple
sheets.
----------------------------------------------------
'--method 2 multiple Excel sheets to multiple Access Tables
Sub GetDataFromExcel2()
Dim dbsTemp As Database
Dim tdfLinked As TableDef, i As Integer
Dim arrShts As Variant, arrTblsXls As Variant
Dim arrTblsAcc As Variant
arrShts = Array("Sheet1$", "Sheet2$", "Sheet3$")
arrTblsXls = Array("tblSheet1", "tblSheet2", "tblSheet3")
arrTblsAcc = Array("tbl1", "tbl2", "tbl3")
Set dbsTemp = CurrentDb
For i = 0 To Ubound(arrShts)
Set tdfLinked = dbsTemp.CreateTableDef(arrTblsXls(i))
tdfLinked.Connect = _
"Excel 5.0;HDR=YES;IMEX=2;DATABASE=C:\Dir1\Book1.xls"
tdfLinked.SourceTableName = arrShts(i)
dbsTemp.TableDefs.Append tdfLinked
DoCmd.RunSql "Select * Into " & arrTblsAcc(i) & " From " & arrTblsXls
End Sub
--------------------------------------------------
HTH
Rich
*** Sent via Developersdex
http://www.developersdex.com ***