Here is another method using Update. Update is needed to update the MDB as the recordset is disconnected until then. AddNew is used to add a new record.
Sub ADO()
' the Microsoft ActiveX Data Objects 2.x Library
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, Row As Integer, s As String
'On Error GoTo EndNow
' Set window and calc off to speed updates
SpeedOn
' Database information
'DBFullName = "C:\myfiles\vbabook\Names.mdb"
DBFullName = "u:\Material\ADO\NWind.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
' Next two lines critical to work in QPro properly. Excel does not need them.
Recordset.CursorType = adOpenKeyset
Recordset.LockType = adLockOptimistic
With Recordset
' Filter
Src = "SELECT * FROM Orders "
'Src = Src & "and CategoryID = 30"
Recordset.Open Source:=Src, ActiveConnection:=Connection
' Cells.Clear 'Used in Excel to clear a sheet
' Write the field names
'For Col = 0 To .Fields.Count - 1
'Range("A1").Offset(0, Col).Value = Recordset.Fields(Col).Name 'Excel method
'Next
If .RecordCount < 1 Then GoTo EndNow 'Query found no matching records
' Write the recordset by Excel method
'Range("A1").Offset(1, 0).CopyFromRecordset Recordset
'Add a new record (not pushed to the database until Update)
MsgBox CStr(.RecordCount), vbInformation, "#Records"
.AddNew
Recordset("ShipName") = [Name!A2]
Recordset("ShipAddress") = [Address!B6]
Recordset("ShipCity") = Worksheets("City").Range("C3")
.Update
MsgBox CStr(.RecordCount), vbInformation, "#Records"
End With
EndNow:
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
' Reset window and calculation
SpeedOff
End Sub
Bookmarks