ADODB Connection - Header text not extracted & read-only issue - vba

I am delving into the world of VBA data connections, and would appreciate some assistance. The code below is what I have so far, but there are a couple of oddities I can't figure out.
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = "C:\USERS\NAME\DOCUMENTS\VBA Work\Data Source.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLQry = "SELECT * From [Sheet1$]"
mrs.Open sSQLQry, Conn
Sheet3.Range("A1").CopyFromRecordset mrs
mrs.Close
Conn.Close
End Sub
This code works, however:
The data pulled in doesn't include Row1 of the dataset (so the headers aren't pulled in)
If the source workbook 'Data Source.xlsx' is open. The code will cause the workbook to open again but in read-only mode. Can this be avoided?
Can the connection string be edited so that the source file is never locked out? ie. queried in Read-Only mode other users can open it whilst the query is being completed?
Any help is appreciated
Thanks
Caleeco

Try this:
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String,i as integer
'DBPath = ThisWorkbook.FullName
DBPath = "C:\USERS\NAME\DOCUMENTS\VBA Work\Data Source.xlsx"
sconnect= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & _
DBPath & """;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX = 1"""
Conn.Open sconnect
sSQLQry = "SELECT * From [Sheet1$]"
mrs.Open sSQLQry, Conn
if rs.recordcount>0 then
rs.movefirst
for i=0 to rs.fields.count-1
'read here the headers and add them to your sheet in row 1
Sheet3.Cells(1, i + 1) =rs.Fields(i).Name
next
end if
Sheet3.Range("A2").CopyFromRecordset mrs
mrs.Close
Conn.Close
End Sub

Related

Read SQL Server query for ADODB.Connection from external file or from variable

I have this Excel VBA code:
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim query As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=xxxx.xxx.xxxx.xxx,xxxx;" & _
"Initial Catalog=mydb;" & _
"Trusted_Connection=yes;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("")
ActiveSheet.Range("A2").CopyFromRecordset rs
...
End Sub
all works fine.
The issue is in this section: Set rs = conn.Execute("")
My select statement query is just too big, split it into continuation lines is not practical.
Is there a way of reading the query text from a file, or from a variable?
Thank you very much
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim query As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=xxxx.xxx.xxxx.xxx,xxxx;" & _
"Initial Catalog=mydb;" & _
"Trusted_Connection=yes;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
'read SQL from file
query = GetContent("C:\Stuff\myQuery.txt")
Set rs = conn.Execute(query)
ActiveSheet.Range("A2").CopyFromRecordset rs
...
End Sub
'read all file content
Function GetContent(f As String) As String
GetContent = CreateObject("scripting.filesystemobject"). _
opentextfile(f, 1).readall()
End Function
Alternatively, store your SQL in a worksheet cell and read it from there.
You don't have to use continuation lines, you can append the strings and append a vbCrLf character. e.g.
Dim sSQL as string
sSQL = "SELECT" & vbCrLf
sSQL = sSQL & "AField" & vbCrLf
sSQL = sSQL & ",BField" & vbCrLf
sSQL = sSQL & ",(SELECT XField FROM AnotherTable ..........) as XField" & vbCrlf
'and so on and so on
Set rs = conn.Execute(sSQL)
You can build very long SQL statements this way.

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

Query range in activeworkbook using ADODB

I'm trying to write some VBA that can query a named range in VBA using SQL. Currently, it works reasonably well, but i have the problem that every time i run the macro a read-only instance of the worksheet is opened. I want to use the macro to query ranges within the same workbook without opening a read-only copy.
Here is my code
Public Sub QueryAndOutputToCell(ByVal query As String, rng As Range)
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim DBFullName, connString, SQL As String
DBFullName = ThisWorkbook.path & "\" & ThisWorkbook.name
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DBFullName & "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
conn.connectionString = connString
conn.Open ' Read-only copy is opened here
conn.commandtimeout = 0
Dim cubeData As ADODB.Recordset
Set cubeData = New ADODB.Recordset
cubeData.Open query, conn, adOpenDynamic, adLockReadOnly
rng.CopyFromRecordset cubeData
cubeData.Close
conn.Close
Set cubeData = Nothing
Set conn = Nothing
End Sub
Do anyone know if this is possible?

VBA: type mismatch -- how to pass ADODB.Recordset object to subroutine?

I encountered a type mismatch error when passing a ADODB.Recordset object to a subroutine. See the code nugget below.
Sub CreateRS()
Dim oCONN As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim strSQL As String
Dim strConn As String
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes;"";"
Set oCONN = New ADODB.Connection
oCONN.Open strConn
strSQL = "SELECT * FROM mytable"
Set oRS = New ADODB.Recordset
oRS.Open strSQL, oCONN
' type mismatch error for the next statement
ProcessRS (oRS)
End Sub
Sub ProcessRS(ByRef RS As ADODB.Recordset)
....
End Sub
Did quite a bit of searches, yet didn't find a correct answer. Can anyone point out what is the right syntax to use here? Thanks!

Excel 2007 VBA - Error: "Object variable or With Block variable not set" when using OLEDB connection to another Excel File

So my problem is that between 2 different computers my connection to the string no longer can open a connection.
Here is what I have:
Dim sFileName As String
Dim sFilePath As String
sFileName = "DataSource.xls"
sFilePath = "C:\test\testingData\"
Dim sConn As String
sConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sFilePath & sFileName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
Dim errorObject As ADODB.Error
Set errorObject = CreateObject("ADODB.Error")
On Error GoTo ErrorDisplay:
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.Open sConn
Dim rst As ADODB.Recordset '* Record Set
Set rst = New ADODB.Recordset
rst.Open sSql, conn, adOpenForwardOnly
Worksheets(1).Range("A2").CopyFromRecordset rst
sSQL = "SELECT * FROM [MySheet$] WHERE [Status] = 2 AND [DocNo] LIKE '%-A%'
When I run this section of code on one computer it runs perfectly as I built it. When I try it on a similar computer it keeps giveing an error "Object variable or With Block variable not set". I have found out that the problem is with the conn.Open sConn but not sure what is causing it.
I have been searching about looking for a solution but as of yet I have not found anything that worked.
Additional Info:
Both computers:
Windows 7 x64
Excel 2007 x32
Any thoughts as to why this would not work?
--Update:
I just finished trying the excel file with the macro out on a 3rd windows 7 computer and that one works fine.
--Update:
I have just tried running the program from
sFilePath = "C:\Users\FirstName.LastName\Desktop\"
and
sFilePath = "C:\Users\FirstName.LastName\Desktop\Test\"
The thing I would really like to know is that it's working from the "C:\Users\FirstName.LastName\Desktop\Test\" but none of the others???
Are you sure that the Primary Interop Assemblies are installed on both computers?
You may try below code.
' Add reference to Adodb library
Dim conn As ADODB.Connection
Public Function CreateConnection() As Boolean
On Error GoTo ErrorRet
Dim X As Integer
Dim sConn As String
Dim sFileName As String
Dim sFilePath As String
X = 0
Reconn:
X = X + 1
sFileName = "DataSource.xls"
sFilePath = "C:\test\testingData\"
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sFilePath & sFileName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
Set conn = New ADODB.Connection
conn.Open sConn
CreateConnection = True
Exit Function
ErrorRet:
If Err.Number = -2147467259 Then
GoTo Reconn
Else
If X > 5 Then
CreateConnection = False
Else
GoTo Reconn
End If
End If
End Function
Sub test()
Dim sSql As String
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
If CreateConnection Then
sSql = "SELECT * FROM [MySheet$]"
rst.Open sSql, conn
Worksheets(1).Range("A2").CopyFromRecordset rst
End If
End Sub