Excel automation error when running SQL update statement - sql

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

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.

Related

VBA DAO Accessing Excel 2010 like database

I am trying to use DAO to write some VBA into Excel 2010. I want to be able to access an excel 2010 workbook like a database. I am trying to open a workbook instead of a mdb file. Is there any way I can use DAO with an excel workbook instead of an actual database?
Dim db As Database
Dim rst As Recordset
Dim SQL As String
SQL = "SELECT * From [DataSheet$]"
Set db = OpenDatabase(ThisWorkbook.FullName)
Set rst = db.OpenRecordset(SQL)
'displays the first record and first field
MsgBox rst.Fields(0)
'close the objects
rst.Close
db.Close
'destroy the variables
Set rst = Nothing
Set db = Nothing
I borrowed code from here http://www.excel-spreadsheet.com/vba/dao_ado.htm
Actually, you can connect to Excel workbooks using DAO by extending the arguments of DAO.OpenDatabase():
Dim conn As Object, db As Object, rst As Object
Set conn = CreateObject("DAO.DBEngine.120")
' EXCEL OLDER VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xls", False, True, "Excel 8.0;HDR=Yes;")
' EXCEL CURRENT VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xlsx", False, True, "Excel 12.0 Xml;HDR=Yes;")
Set rst = db.OpenRecordset("SELECT * FROM [SheetName$]")
MsgBox rst.Fields(0)
rst.Close
db.Close
Set db = Nothing
Set conn = Nothing
Set rst = Nothing
I figured out my issue. Using the code below you can access an excel file and treat it like a database.
Option Explicit
Private Sub btnConnect_Click()
Dim dataConection As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim SQL As String
Dim DBPath As String
Dim connectionString As String
DBPath = ThisWorkbook.FullName 'Refering the sameworkbook as Data Source
'You can provide the full path of your external file as shown below
connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
'Open connection
dataConection.Open connectionString
'Create SQL query
SQL = "SELECT * From [DataSheet$]"
'Open record set (query or table, connection)
mrs.Open SQL, dataConection
Do While Not mrs.EOF
Debug.Print " " & mrs!Name
mrs.MoveNext
Loop
mrs.Close
'Close Connection
dataConection.Close
End Sub

VBA: microsoft access database engine could not find the object (SQL query worksheet table)

I am getting the following error message, on the line rs.Open strSQL, cn , when trying to do a SQL select statement against a table range in an Excel spreadsheet:
The Microsoft Access database engine could not find the object
'Sheet1$A1:NC3'. Make sure the object exists and that you spell its
name and the path name correctly. If 'Sheet1$A1:NC3' is not a local
object, check your network connection or contact the server
administrator
I have run through the various Stack Overflow side bar suggestions for similar questions, and let Google have a run at it, but i have still not resolved this.
The object is local - check
Workbook is the current open workbook which is saved to the desktop -check
Network connection fine - check
Observations
Putting the SQL string as "Select * from [Sheet1$];" works fine.
Extend that, by adding the range reference, and the error comes back i.e. "Select * from [Sheet1$A1:NC3];" does not work.
As noted in comments, up to column IV i.e. [Sheet1$A1:IV3] is ok; column IW onward, and error message is back.
Note: Debug.Print confirms
ListObjects("Table1").Range.Address as $A$1:$NC$3
rngAddress is [Sheet1$A1:NC3];
Can anyone please spot what i have done incorrectly? Or suggest a workaround so i can still use this range (and preferably not select the entire sheet)
Here is the full code:
Option Explicit
Public Sub TestSQL()
'Tools > references > Microsoft ActiveX Object Library
Dim wb As Workbook
Dim wsSource As Worksheet
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Sheet1")
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
Dim rngAddress As String
rngAddress = "[" & wsSource.Name & "$" & Replace(wsSource.ListObjects("Table1").Range.Address, "$", "") & "];"
strSQL = "SELECT * FROM " & rngAddress
rs.Open strSQL, cn
End Sub
Environment: Windows 8, Excel 2016 64 bit.

Copy rows from access table to Excel

I have the following code
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ActionList.accdb"
strSql = "SELECT * FROM Actionlist;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
My purpose is to get all rows from a certain table to copy in my Excel sheet. I though something this easy would be all over the internet, but I cannot seem to find it. I would like the rows to start from A2, since I've already added the access table to my worksheet by using the built-in function of Excel. I want to do this manually however, to add certain filters.
You will need, what you have, but also
for f= 0 to rs.fields.count-1
range("a1").offset(0,f).value=rs.fields(f).name
next f
range("a2").copyfromrecordset rs
Switch do DAO, so that CopyFromRecordset() will work:
Private Sub CommandButton1_Click()
Dim Dbs As DAO.Database
Dim rs As DAO.Recordset
Dim strSql As String
Set Dbs = OpenDatabase("C:\ActionList.accdb")
strSql = "SELECT * FROM Actionlist;"
Set rs = Dbs.OpenRecordset(strSql)
'Add Head lines:
for i= 0 to rs.fields.count-1
range("a1").offset(0,i).value=rs.fields(i).name
next f
'Add Data:
range("a2").CopyFromRecordset rs
'Colse resources:
rs.Close
Set rs = Nothing
Dbs.Close
Set Dbs= Nothing
End Sub

Saving Results of Access Query To Worksheet Excel VBA

I cant seem to find an easy way of doing outside of just accessing the SQL from ACCESS SQL View and doing it manually. Is there some magic way to use this code below and do that?
Its worth pointing out that I am trying to do this from Excel's VBA.
Private Sub tryagain()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "C:\Users\Ashleysaurus\Desktop" & "\" & "xyzmanu3.accdb"
End With
con.Execute "Invoice Query"
'How do output to Worksheet?
rs.Close
cmd.ActiveConnection.Close
End Sub
Simply use the ADO recordset object which you initialize, call the query, and then run the Range.CopyFromRecordset method (specifying the leftmost worksheet cell to place results).
Also, see the changed connection open routine with proper connection string. And because recordsets do not pull in column headers automatically but only data, an added loop was included iterating through recordset's field names.
Private Sub tryagain()
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConnection As String
Dim i as Integer, fld As Object
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Users\Ashleysaurus\Desktop\xyzmanu3.accdb';"
con.Open strConnection
rs.Open "SELECT * FROM [Invoice Query]", con
' column headers
i = 0
Sheets(1).Range("A1").Activate
For Each fld In rs.Fields
ActiveCell.Offset(0, i) = fld.Name
i = i + 1
Next fld
' data rows
Sheets(1).Range("A2").CopyFromRecordset rs
rs.Close
cn.Close
End Sub
By the way, this same above setup can even query Excel workbooks as the Jet/ACE SQL Engine is a Windows technology (.dll files) available to all Office or Windows programs.
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Workbook.xlsm';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
strSQL = "SELECT * FROM [Sheet1$]"

How do I open a CSV File via VBA Script in a Powerpoint PPTM

I have a complicated Powerpoint Presentation that eventually gets exported as a bunch of single slides via ISpringPro
Because of the export process, the navigation links between the slides need to be managed so that individual exported slides can navigate to others.
I'm trying to write a VBA Script to allow a global find & replace of all Hyperlinks in the powerpoint.
My prototype version works fine where you type a single URL in an InputBox and a second url in a second Input Box to find and replace. But I'd like to just read all this info in from a 2 Column CSV file and have it look overall of them.
I'm now having trouble getting VBA to open the CSV file using the ADODB Connection. I think I might be missing a reference but VBA really isn't my strong suit.
I've pasted the code below. but it's blowing up on the Set cn = New ADODB.Connection saying that it doesn't know what that type is.
Am I missing some sort of assembly reference ?
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
Dim csvPath As String
Dim csvFolder As String
csvPath = .SelectedItems(1)
csvFolder = StripFilename(csvPath)
Dim cn As Object
Dim rs As Object
Dim strsql As String
Dim col As Integer
strsql = "SELECT OLDURL,NEWURL FROM " & csvPath
Dim cn As ADODB.Connection, rs As ADODB.Recordset, f As Integer
Set cn = New ADODB.Connection
'On Error Resume Next
cn.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
"Dbq=" & strFolder & ";" & _
"Extensions=csv,tab,txt;"
'On Error GoTo 0
If cn.State <> adStateOpen Then Exit Sub
Set rs = New ADODB.Recordset
'On Error Resume Next
rs.Open strsql, cn, adOpenForwardOnly, adLockReadOnly, adCmdText
'On Error GoTo 0
If rs.State <> adStateOpen Then
cn.Close
Set cn = Nothing
Exit Sub
End If
Dim iRet As Integer
For f = 0 To rs.Fields.Count - 1
iRet = MsgBox(rs.Fields(f).Name)
Next f
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End With
Scratch that.
I needed to run power point as Administrator and then in the Macro Editor go to
Tools > References >
and add a reference to the latest Microsoft ActiveX Data Objects library.