-
Solved: Import Multiple Tables
How do I get Excel to import multiple access tables into excel
I have the following to do 1 table
[vba]Sub GetTable()
Dim DBFullName As String
Dim Cnct As String, src As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
' Database information
DBFullName = "C:\Program Files\FieldSalesApplication\PremierPlusField.mdb"
' Open the connection
Set Connection = New ADODB.Connection
Cnct = "Provider=Microsoft.Jet.OLEDB.4.0; "
Cnct = Cnct & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Cnct
' Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
' Filter
src = "SELECT * FROM TblQuote"
.Open Source:=src, ActiveConnection:=Connection
' Write the field names
Sheets("tblQuote").Select
Cells.Clear
For Col = 0 To Recordset.Fields.Count - 1
Range("A1").Offset(0, Col).Value = Recordset.Fields(Col).Name
Next
' Write the recordset
Range("A1").Offset(1, 0).CopyFromRecordset Recordset
Set Recordset = Nothing
End With[/vba]
But without replicating all that for every table I want is there an easier/more logical approach
-
Just make the GetTable subroutine general in which you pass 2 arguments:
1. the name of the table used in the SQL statement
2. the sheet where the recordset should be written to
[vba]Sub GetTable(tbl As String, sht As Worksheet)
'replace relevant lines of code with these below
src = "SELECT * FROM " & tbl
sht.Select
End Sub[/vba]
Call the subroutine like this:
[vba]GetTable "TblQuote", Worksheets("tblQuote")
GetTable "tblSuppliers", Worksheets("sheet2")[/vba]
-
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules