This is Part 6 of 7 in a tutorial on using code to integrate Excel and Access.
In the sample file, Table Download has a button with the caption Update Current Record. Do the following to edit a single record:
You can check this by deleting all data on this sheet, then downloading the table again.
Note:
The constant is shown below. It needs to go before the first Sub procedure in the module:
Const TARGET_DB = "DB_test1.mdb"
The code for this example is shown below. The code does the following:
Sub AlterOneRecord() Dim cnn As ADODB.Connection Dim rst As ADODB.Recordset Dim fld As ADODB.Field Dim MyConn Dim lngRow As Long Dim lngID As Long Dim j As Long Dim sSQL As String 'determine the ID of the current record and define the SQL statement lngRow = ActiveCell.Row lngID = Cells(lngRow, 1).Value sSQL = "SELECT * FROM tblPopulation WHERE PopID = " & lngID Set cnn = New ADODB.Connection MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB With cnn .Provider = "Microsoft.Jet.OLEDB.4.0" .Open MyConn End With Set rst = New ADODB.Recordset rst.CursorLocation = adUseServer rst.Open Source:=sSQL, _ ActiveConnection:=cnn, _ CursorType:=adOpenKeyset, _ LockType:=adLockOptimistic 'Load contents of modified record from Excel to Access. 'do not load the ID again. For j = 2 To 7 rst(Cells(1, j).Value) = Cells(lngRow, j).Value Next j rst.Update ' Close the connection rst.Close cnn.Close Set rst = Nothing Set cnn = Nothing End Sub
Note the cursor type in this example. Instead of adOpenForwardOnly or adDynamic, which we used in the samples where we were writing whole records to the database, this code uses adOpenKeyset.