PDA

View Full Version : Error Importing XLS sheet into Access via VBA



Dragonlancer
07-25-2008, 08:49 AM
I have been :banghead: trying to import and Excel sheet into a table in Access. I have also added DAO 3.6 to the references. When I try running the code I keep getting "User-Defined Type Not Defined" on "Dim cn As ADODB.Connection"......

I hope someone out there has ran into this issue on Excel & Access 2003 and has a possible solution. :help

Sincerely, DragonLancer


Option Explicit
Sub SendToAccess2()
' Exporting to Access DATABASE TABLE
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim r As Long
' connect to the Access database
Set cn = New ADODB.Connection
' NAME CORRECT DATABASE
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\TESTBED\Data Analysis.mdb"
' open a recordset
Set rs = New ADODB.Recordset
' NAME THE CORRECT DB TABLE TO EXPORT DATA TO
rs.Open "All Employee Report", cn, adOpenKeyset, adLockOptimistic, adCmdTable

' all records in a table
' deleting existing database data
Do Until rs.EOF '<<<loop until End of File marker is reached
rs.Delete
rs.MoveNext
Loop

r = 1 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record add values to each field in the record
.Fields("EVP / GE") = Range("A" & r).Value
.Fields("Generalist") = Range("B" & r).Value
.Fields("DEPTID") = Range("C" & r).Value
.Fields("Mgr EmpNo") = Range("D" & r).Value
.Fields("DEPTID MGR") = Range("E" & r).Value
.Fields("EMPNO") = Range("F" & r).Value
.Fields("NAME") = Range("G" & r).Value
.Fields("JOBTITLE") = Range("H" & r).Value
.Fields("JOBCODE") = Range("I" & r).Value
.Fields("GRADE") = Range("J" & r).Value

.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

Bob Phillips
07-25-2008, 08:55 AM
DAO is NOT ADO, they are different beats. ADd a reference to Microsoft ActiveX Data Objects Library.