Spreadsheet to access


G

Guest

Please,help
When i run the code below i get message:
"the connection can not be used to perform this operation. it is either
closed or invalid in this context



Private Sub ADOFromExcelToAccess()

Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long

Set cn = New ADODB.Connection
'Replace with the path to your database
cn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Documents and
Settings\Boris\My Documents\test/" _
& "Data.mdb;Persist Security Info=False"

Set rs = New ADODB.Recordset
rs.Open "test", cn, adOpenKeyset, adLockOptimistic, adCmdTable

r = 2 ' the starting 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("FieldName1") = Range("A" & r).Value
..Fields("FieldName2") = Range("C" & r).Value
..Fields("FieldName3") = Range("D" & r).Value
..Fields("FieldName4") = Range("F" & r).Value
' add more fields if necessary...
..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
 
Ad

Advertisements

G

Guest

boris said:
Please,help
When i run the code below i get message:
"the connection can not be used to perform this operation. it is either
closed or invalid in this context



Private Sub ADOFromExcelToAccess()

Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long

Set cn = New ADODB.Connection
'Replace with the path to your database
cn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Documents and
Settings\Boris\My Documents\test/" _
& "Data.mdb;Persist Security Info=False"

Set rs = New ADODB.Recordset
rs.Open "test", cn, adOpenKeyset, adLockOptimistic, adCmdTable

r = 2 ' the starting 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("FieldName1") = Range("A" & r).Value
.Fields("FieldName2") = Range("C" & r).Value
.Fields("FieldName3") = Range("D" & r).Value
.Fields("FieldName4") = Range("F" & r).Value
' add more fields if necessary...
.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

Hi Boris,

I think you need to use

cn.Open

before

Set rs = New ADODB.Recordset
rs.Open "test", cn, adOpenKeyset, adLockOptimistic, adCmdTable

Hope that helps.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top