Question

I have the following code that is intended to update an Access database however when i run the macro i get an automation error. If i execute the SELECT statement, it runs fine. I don't need to select any values from the worksheet to update the database.

Private Sub UpdateRecord()
ThisWorkbook.Activate
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\temp\test.mdb"

strSql = "UPDATE table1 SET Name1='Test' WHERE Object_ID=2076;"

'strSql = "SELECT * FROM table1;"

cn.Open strConnection
Set rs = cn.Execute(strSql)

Worksheets("Sheet1").Select
Sheets("Sheet1").Range("A6").CopyFromRecordset rs

rs.Close
Set rs = Nothing

cn.Close
Set cn = Nothing

End Sub
Was it helpful?

Solution

Unfortunately I cannot repeat your situation and use ADODB. I recommend you to use native DAO library to work with MSJet (Access) database.

Sub qwe()
  Dim dbe As New DAO.DBEngine
  Dim dbs As DAO.Database
  Dim rst As DAO.Recordset

  Set dbs = dbe.OpenDatabase("C:\Users\nmaksudov\Documents\Database2.accdb")
  dbs.Execute("UPDATE Table1 SET Field2='zzz' WHERE Field1=2")
  Set rst = dbs.OpenRecordset("select * from Table1")

  While Not rst.EOF
    MsgBox rst.Fields(1).Value & "," & rst.Fields(2).Value
    rst.MoveNext
  Wend

  MsgBox rst.RecordCount
End Sub

This should work perfect. Just add DAO library of correct version to your project. To find correct library open VBA editor in Access and choose Tools/References… menu. Find data access library in the list (in my case it is «Microsoft Office 12.0 Access database engine Object Library» or it could be «DAO 3.6» etc. Depens on version). After that open the same dialog in Excel and add the the object library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top