I am a newbie and just started learning VBA. I am trying to read/import data from a table in Access into a tab in 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 - located 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 exact).
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
And here is 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
I am not sure how to continue my coding...My target cells are C5:M32 in my spreadsheet - sheets "happy"...How does the coding import the data correctly into the cells belongs to each column with different header names...and 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..
I apologize if I cannot explain this with a good logic..If any programming guru can help me on skype, I would appreciate too!
It is nice to join this community!
Any help is appreciated!