Excel VBA: Can I query external excel without opening the target file? - vba

I want to omit the line ".Open" below but it said "Operation is not allowed when the object is closed", are there any methods to query the file without opening it?
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & "C:\data.xls" & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Set rs = cn.Execute("SQL statement here")

You open a connection, not the file itself.
Thus, it is really what you need.
Try the following and see that the file is not opened:
Option Explicit
Public Sub TestMe()
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & "C:\DB.xlsm" & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Set rs = cn.Execute("SELECT * FROM [Sheet1$]")
Do Until rs.EOF
Debug.Print rs.Fields.Item(1), rs.Fields.Item(2)
rs.MoveNext
Loop
'cn.Close <- you need this only if you work with some crazy guys, who do not
'understand the open-close principle
End Sub
If the file is shared between many users, then a ReadOnly permission of the connection (simply change the ConnectionString as shown) can be used:
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & "C:\DB.xlsm" & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES application intent=ReadOnly"";"
.Open
End With

Related

Error: 3704 Operation is not allowed when the object is closed

I am trying to open an Excel sheet using ADODB connection, but I am getting the following error when I try to execute the query although the name of the worksheet is correct:
Error number: 3704
Error Description:Operation is not allowed when the object is closed
I have gone through most of the answers provided online and I still can find my answer as I already have what was missing in the answers I read.
Here is my code:
Dim objConn
Set objConn = Server.CreateObject("ADODB.Connection")
Dim ext : ext = GetFileExt(filename)
If ext = "xlsx" Then
With objConn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = _
"Data Source=" & Server.MapPath("../import/" & filename) & ";" & _
"Extended Properties=Excel 12.0;"
.CursorLocation = adUseClient
.Open
End With
End If
Dim sql
sql = "SELECT * FROM [" & worksheet & "$]"
Dim objRs
Set objRs = objConn.Execute(sql)
response.write "err.number: " & Err.Number '3704
response.write "err.Description: " & Err.Description 'Operation is not allowed when the object is closed

Excel, VBA, SQL - Retrieve data from another workbook / Error

I want to retrieve data from a closed workbook.
My code is
fileName = "the path\test.xlsx"
With CreateObject("ADODB.Connection")
.CommandTimeout = 500
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& fileName & ";" & "Extended Properties=""Excel 12.0;HDR=YES;Readonly=true"";"
.Open
ThisWorkbooks.Worksheets("new").Range("A1").CopyFromRecordset .Execute("select * from [source$B1]")
.Close
End With
I have some error, 424:object required, object doesn't found... I think it is a syntax problem.
The purpose is to retrieve data from cells and put in the other sheet/workbook
thanks for your help
Three things:
Unless you defined "ThisWorkbooks" somewhere, I think it should be "ThisWorkbook".
Using this method, I have only ever been able to fetch ranges that contain ":" in them, so change source$B1 to source$B1:B1.
Since you only want one cell, you should turn the HDR (header) option off.
fileName = "the path\test.xlsx"
With CreateObject("ADODB.Connection")
.CommandTimeout = 500
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& fileName & ";" & "Extended Properties=""Excel 12.0;HDR=No;Readonly=true"";"
.Open
ThisWorkbook.Worksheets("new").Range("A1").CopyFromRecordset
.Execute("select * from [source$B1:B1]")
.Close
End With

Excel VBA SQL error, Connection failed

I get the following error when I try to run an internal sql query in my Excel spreadsheet.
Error 2147467259 - Method of 'Execute' object' _Connection' failed.
Also when I run the code with breakpoints, I can get an automation error. I am querying in Excel 2013 (15.0.5023.1000).
With conn_obj
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & report_name & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
On Error GoTo err_SQL
SQL = query
Set rs = conn_obj.Execute(SQL) 'error here
Update: I replaced the above code with the below, I am getting an error on
Format of the initialization string does not conform to the OLE DB Specification.
Dim sSQLString As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Let DBPath = report_name 'Path here
Let sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath & ";Extended Properties='text;HDR=YES;';"
Conn.Open sconnect
sSQLString = query ' query here
mrs.Open sSQLString, Conn
could you try changing the below
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
to
"Extended Properties='Excel 12.0 Xml;HDR=YES';"
if not advise what report_name is equal to.
alternatively try the below:
Dim sSQLString As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Let DBPath = "" 'Path here
Let sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath & ";Extended Properties='text;HDR=YES;';"
Conn.Open sconnect
sSQLString = "" ' query here
mrs.Open sSQLString, Conn

Setting a connection to an access database in VBA crashes excel

This is the code I use to open a connection to an access database from excel. It used to work for more than a year.
Set dbname = New ADODB.Connection
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open theconnection
End With
By trial an error I've come to the conclusion that this line is causing the problem.
Set dbname= New ADODB.Connection
The problem began after an automatic update of my PC
My Excel version 2016 MSO (16.0.7726.1036) 32-bit
Please let me know if you have run also into this problem, and if you know any fix or workaround.
try to uncheck your 'ActiveX Data Objects' references and add them back:
Tools - References
or
use object to define a database:
Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")
or
if you create connection variable like this:
Dim con as New ADODB.Connection
change it to:
Dim con as ADODB.Connection
Set con = New ADODB.Connection
Maybe
Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open theconnection
End With
I used like this , all code
Dim Rs As Object
Dim strConn As String
Dim i As Integer
Dim strSQL As String
strSQL = "select * from [table] "
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0;"
Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn
If Not Rs.EOF Then
With Ws
.Range("a1").CurrentRegion.ClearContents
For i = 0 To Rs.Fields.Count - 1
.Cells(1, i + 1).Value = Rs.Fields(i).Name
Next
.Range("a" & 2).CopyFromRecordset Rs
End With
End If
Rs.Close
Set Rs = Nothing

VBA ADO connection to .xlsx file

I am trying to copy data from a closed Excel 2007 workbook (.xlsx) using an ADO connection.
I have the connection string working. But I get an automation error when I try to open the Command in the Recordset (Second to last line).
This may not be clear in the below code so:
"wsSummary" is a worksheet object
"strSourceFile" is a string with the target data I need to copy from (e.g. Template.xlsx)
strSourceFile = wsSummary.Cells(nFirstRow + 4, 7)
strSheetSource = "Sheet1"
strSQL = "SELECT * FROM [" & strSheetSource & "]"
Set dbConnection = New ADODB.Connection
With dbConnection
.Provider = "Microsoft.ACE.OLEDB.12.0;"
.connectionString = "Data Source=" & strPOINTDataPath & strSourceFile & _
";Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";"
.ConnectionTimeout = 40
.Open
End With
If dbConnection = "" Then GoTo ErrorText
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = dbConnection
.CommandText = strSQL
End With
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = dbConnection
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open cmd
End With
I think you missed $ character in your SQL statement. Try to change appropriate line into this one:
strSQL = "SELECT * FROM [" & strSheetSource & "$]"
or change strSheetSource variable into this:
strSheetSource = "Sheet1$"