I have a subroutine in excel that I would like to write data to an Access table. I am trying to update a row in the table if it already exists, add it if it does not. Going off
The @@ROWCOUNT
is used for SQL Server not Access but since you are using VBA
you could do something similar to this. Basically create your SQL statements as strings putting in your values that you are checking for. Then run query against the table first to see if the record exists, if it does then do the UPDATE
if not then do the INSERT
. I quickly tested this in MS Access 2003 and it works.
Public Sub test()
Dim sqlStrUpdate As String
Dim sqlStrSelect As String
Dim sqlStrInsert As String
Dim recordSet As recordSet
sqlStrUpdate = "UPDATE table1 SET Field1 = " & 5 & " WHERE id = 3"
sqlStrSelect = "SELECT id FROM table1 WHERE id = 3"
sqlStrInsert = "INSERT INTO table1 (id, Field1, Field2, Field3) VALUES (3, 5, 0, 0)"
Set recordSet = CurrentDb.OpenRecordset(sqlStrSelect)
If recordSet.RecordCount > 0 Then
DoCmd.RunSQL (sqlStrUpdate)
ElseIf recordSet.RecordCount = 0 Then
DoCmd.RunSQL (sqlStrInsert)
End If
End Sub
EDIT: As HansUp pointed out you are querying from Excel, your code could be similar to this:
Public Sub test_new()
Dim cDir_Database As String
Dim DB_Conn As New ADODB.Connection 'Access Connection
Dim DB_RSet As New ADODB.recordSet 'Access Record Set
Dim sqlStrUpdate As String
Dim sqlStrInsert As String
cDir_Database = ".\.\.AccessBD.mdb "
sqlStrUpdate = "UPDATE table1 SET Field1 = " & 10 & " WHERE id = 4"
sqlStrInsert = "INSERT INTO table1 (id, Field1, Field2, Field3) VALUES (4, 5, 0, 0)"
DB_Conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"DBQ=" & cDir_Database & ";"
DB_Conn.Open
DB_Conn.BeginTrans
DB_RSet.Open "SELECT id FROM table1 WHERE id = 4", DB_Conn, adOpenStatic, adLockReadOnly
If DB_RSet.RecordCount > 0 Then
DB_Conn.Execute (sqlStrUpdate)
ElseIf DB_RSet.RecordCount = 0 Then
DB_Conn.Execute (sqlStrInsert)
End If
DB_RSet.Close
DB_Conn.CommitTrans
DB_Conn.Close
End Sub
This has been tested from Excel 2003 to Access 2003 and worked. You need to have the references added to your Excel file for the Microsoft ActiveX Data Objects.