I am trying to read/import data from a table in Access into a tab in an Excel spreadsheet. The data will be names/positions/compensations of certain companies. The headers of the columns in both tables (Access and Excel) are the same.
When I read the data, the logic is - locate the company ID in another Access table and then retrieve the data from the Access table that stores the data (the company ID is important since the table stores the data of every company and ID is used to identify which company's data to extract).
This is the template I got from online:
Sub DAOCopyFromRecordSet(DBFullName As String, TableName As String, _
FieldName As String, TargetRange As Range)
' Example: DAOCopyFromRecordSet "C:\FolderName\DataBaseName.mdb", _
"TableName", "FieldName", Range("C1")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
Set TargetRange = Sheets("MIC").Cells(1, 1)
Set db = OpenDatabase(DBFullName)
Set rs = db.OpenRecordset(AIF_MIC, dbOpenTable) ' all records
'Set rs = db.OpenRecordset("SELECT * FROM " & TableName & _
" WHERE " & FieldName & _
" = 'MyCriteria'", dbReadOnly) ' filter records
' write field names
For intColIndex = 0 To rs.Fields.Count - 1
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
' write recordset
TargetRange.Offset(1, 0).CopyFromRecordset rs
Set rs = Nothing
db.Close
Set db = Nothing
End Sub
My actual code:
Sub DAOCopyFromRecordSet("H:\HAPPY\Happy Folder\Happy DB.mdb", "Happy_Table","A,B,C" ,Sheets("Happy").Range("C5:M32")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
Set TargetRange = Sheets("Happy").Cells(1, 1)
Set db = OpenDatabase(DBFullName,false,false,";pwd=HAPPY")
Set rs = db.OpenRecordset(Happy, dbOpenTable) ' all records
'Set rs = db.OpenRecordset("SELECT * FROM " & Happy & _
" WHERE " & FieldName & _
" = 'MyCriteria'", dbReadOnly) ' filter records
' write field names
For intColIndex = 0 To rs.Fields.Count - 1
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
' write recordset
TargetRange.Offset(1, 0).CopyFromRecordset rs
Set rs = Nothing
db.Close
Set db = Nothing
End Sub
My target cells are C5:M32 in my spreadsheet - sheets "happy".
How do I import the data into the cells belonging to each column with different header names?
Also I have to make sure the coding is giving me the data for the correct company since all companies have the same type information saved in the Access table.