Private Sub SaveRecords()
'* 1. When you are inserting new rows inside your grid,
'* Make sure that you are moving the primary key too:
'* That is move the value in Column 0 just like you
'* would do for the other visible columns.
'* 2. In the Update SQL Statement below, Replace [Key Fieldname] with
'* the name of the primary key you are using in your Document table.
'* 3. As soon as you finish saving your records, IMMEDIATELY reload
'* the data from your table back to the grid, to make sure that
'* the primary key for the newly inserted records are loaded.
Dim lcLngi As Long
Dim lcStrSQL As String
Dim lcLngErrLevel As Long
Dim lcObjConn As ADODB.Connection
Dim lcStrConnString As String
On Error GoTo ErrHandler
Set lcObjConn = New ADODB.Connection
lcStrConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=c:\winnt\inventory.mdb;" _
& "User Id=Admin;Password=;"
lcObjConn.Open lcStrConnString
With MSFlexGrid1
lcLngErrLevel = 1000
For lcLngi = 1 To .Rows - 1
'* We check if there is a primary key in the first column of the grid
If Len(Trim$(MSFlexGrid1.TextMatrix(lcLngi, 0))) > 0 Then
'* if so then Record already exist in database, we update it here
lcStrSQL = "UPDATE Document " _
& "SET Folder = '" & .TextMatrix(lcLngi, 1) & "', " _
& "Name = '" & .TextMatrix(lcLngi, 2) & "', " _
& "FileNo = '" & .TextMatrix(lcLngi, 3) & "' " _
& "WHERE [Key Fieldname] = " & CLng(.TextMatrix(lcLngi, 0)) '* Replace with your primary key here!
Else
'* Else Insert new record
lcStrSQL = "INSERT INTO Document(Folder, FileNo, Name) " _
& "VALUES('" & .TextMatrix(lcLngi, 1) & "','" _
& .TextMatrix(lcLngi, 2) & "','" _
& .TextMatrix(lcLngi, 3) & "')"
End If
'* Execute SQL statement using an ADO Connection
lcObjConn.Execute lcStrSQL
Next
End With
Set lcObjConn = Nothing
Exit Sub
ErrHandler:
Set lcObjConn = Nothing
MsgBox Err.Number & ": " & Err.Description
End Sub