Query MS Excel Table using SQL - sql

I found this code to use sql to query a MS Excel table. However, when I run it I get a message stating that the object "Sheet5$" could not be found. There is a table called "Table" on Sheet 5 of the workbook that I am running the code on.
How can I get this code to work
'Reference: Microsoft ActiveX Data Objects x.x Library
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
'Not the best way to refer to a workbook, but convenient for
'testing. it is probably best to refer to the workbook by name.
strFile = ActiveWorkbook.FullName
'Connection string for 2007/2010
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0 xml;HDR=Yes;"";"
cn.Open strCon
'SQL query string
sSQL = "SELECT * FROM [Sheet5$]"
rs.Open sSQL, cn

Related

VBA Schema Table Doesnt Include Newly Added Worksheet

I have a VBA Code that connects to the workbook itself to execute SQL queries. The macro adds Worksheets during runtime.
E.g. ThisWorkbook.Sheets.Add.Name = "TempSheet"
After adding this worksheet, the VBA Macro adds data on the TempSheet.
I will be executing SQL query against the newly added worksheet using this code:
Dbase = ThisWorkbook.FullName
Connection_string = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Dbase & ";" & _
"Extended Properties=""Excel 12.0;HDR=YES"";"
Set cn = New ADODB.Connection
cn.Open Connection_string
SQL_String = "SELECT * FROM [TempSheet$A1:U182]"
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open SQL_String, cn
On the line where it executes the query at rs.Open, I get an error saying
The Microsoft Access database engine could not find the object 'TempSheet$A1:U182'. Make sure the object exists and that you spell its name and the path name correctly. If 'TempSheet$A1:U182' is not a local object, check your network connection or contact the server administrator.
I am very sure that the Worksheet name matches but still it seems that VBA ADO cannot find the newly added worksheet on the workbook.
Appreciate your thoughts on this.

Run Excel SQL on Existing Sheet - Invalid Sheet/Table

Goal: Run SQL against data in an existing Excel worksheet.
I'm running the following code on an existing Excel worksheet. All ADO connections are working but when I run the SQL statement, it tells me that my table is invalid. Should I be passing the name of the worksheet OR the name of the table? I have tried both. Nothing works.
It errors when opening the recordset ("rs.Open strSQL, cn")
When I use the name of the worksheet in the SQL, I receive the following:
'AG1' is not a valid name. make sure that it does not include invalid characters or punctuation and that is is not too long.
When I use the name of the table, I receive the following:
The Microsoft Access database engine could not find the object 'Table4'. Make sure the object exists and that you spell it's name and the path name correctly. If 'Table4' is not a local object, check your network connection or contact the server administrator.
Thank you in advance.
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL As String
Dim strCon As String
' Declare variables
Dim strFile: strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
' "AG1" is the name of the sheet
' I've tried "Table4" (name of table) without luck
strSQL = "SELECT * FROM [AG1$] where [Language] = 'Spanish';"
' execute SQL query
rs.Open strSQL, cn
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub

How to merge two workbooks with one common column using SQL in VBA

I believe i can do this through Macro as well but i would like to get introduced to ADODB and SQL queries in VBA. The datasets are not in Access but separate workbooks and the SQL query for the two workbooks are as follows:
SELECT getRollpHierRpt.Field1, ['App].[Master Book Name], ['App].[App Book Name], ['App].[Secondary App Book Name], ['App].[App Code], ['App].[App Book Status], ['App].[Book Transit], ['App].[Transit Desc], ['App].[Legal Entity Id], ['App].[Legal Entity Desc]
FROM ['App] INNER JOIN getRollpHierRpt ON ['App].[Book Transit] = getRollpHierRpt.Field1;
The examples i have seen on internet include getting a connection to Access/SQL server but if the datasets are two excel workbooks?
Sub MergeIt()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
With conn1
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\amzubaid\Desktop\Practice Merging\13-10-2017.xlsm;" &
"Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
.Open
End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\amzubaid\Desktop\Practice Merging\20181015-Practice.xlsm;" & "Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
.Open
End With
Dim rsSmall As New Recordset
rsSmall.Open "select [Field1] from [getRollpHierRpt$]", conn1
Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell
rsBig.Open "select [App Code],[Legal Entity Desc]," & rsSmall("Field1") & "
As GetRollPH from [getRollpHierRpt$] where [BookTransit] = " &
rsSmall("Field1"), conn2
r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF 'end if file
rsSmall.Close
conn1.Close
conn2.Close
End Sub
You will need to set a connection to each workbook. In effect this relies on treating each workbook as a table in a database. You must have column headings in each workbook, which are treated as field names. Try this for details
OK So it doesn't seem possible - so one possible workaround is to open the smaller table and then step through it and use the individual values to retrieve the desired records from the larger table: Here's an example using two workbooks called Testfile1 and testfile2. Each contains a sheet called "test" and some data with column headings in testfile2 called "TestC" and "TestD" and the first (linking) filed in testfile1 called "TestA". (This requires a reference to Microsoft Active X Data Objects" library in VBE, Tools, References)
Sub TwoFiles()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
With conn1
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile1.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
.Open
End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile2.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
.Open
End With
Dim rsSmall As New Recordset
rsSmall.Open "select [testA] from [test$]", conn1
Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell
rsBig.Open "select [TestC],[TestD]," & rsSmall("testA") & " As GetRollPH from [test$] where [testC] = " & rsSmall("testA"), conn2
r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF 'end if file
rsSmall.Close
conn1.Close
conn2.Close
End Sub

VBA / ADO QUERY Runs on my computer and fails on coworkers computer

The following code works perfectly fine on my computer. I cannot understand why it's not working on another persons computer. Can someone lead me towards ideas that may help trouble shoot this?
The error (with on error commented out) is that the array isn't being loaded with data. Get an error like "either bof or eof is true for the current record"
Also I can tell you if the on error GoTo NEXTT is left on.. it goes there and tries to erase the array and returns a wrong data type error. Makes me think the array is empty.
I checked Conn.State and I can confirm that the connection is open.
Function sbADO(ban_id, upc_id, div_id)
'Must add Activex data objects libaray 2.8
Dim sSQLSting As String
On Error GoTo nextt
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
'You can provide the full path of your external file as shown below
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Conn.Open sconnect
sSQLSting = "SELECT * From [data$] where BANNER_ID IN (" & ban_id & ") AND UPC_ID IN (" & upc_id & ") AND DIVISION_ID IN (" & div_id & ") " 'Your SQL Statemnt (Table Name= Sheet Name=[DataSheet$])
mrs.Open sSQLSting, Conn
'=>Load the Data into an array
ReturnArray = mrs.GetRows
''OR''
'=>Paste the data into a sheet
'Sheets("Sheet1").Range("A2").CopyFromRecordset mrs
'Close Recordset
mrs.Close
'Close Connection
Conn.Close
'
Exit Function
nextt:
Erase ReturnArray
'mrs.Close
Conn.Close
'MsgBox (ReturnArray(6, 2)) '(feild, row)
End Function
The problem is because
DBPath = ThisWorkbook.FullName <-- the workbook is set to read only.
Removing read only status fixes the issue.
It seems like you're using ADO to query data in the same workbook? That might be for the purposes of simplifying this problem for SO, but it would be easier and faster to get the array you need by referring to the range directly. But in this answer, I'll assume that you really do want to use ADO.
You're trying to use ADO to open the workbook, but you're not specifying the ConnectionString or Open methods with any read-only arguments. Try making these adjustments:
'Add Mode=Read
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";Mode=Read;"
'Add adLockReadOnly
mrs.Open sSQLSting, Conn, , adLockReadOnly

vba query csv files "could not find installable ISAM" error

I intended to write a macro to query both csv and xml files using Access vba. I do not want to parse csv or xml to a temp table in Access.
Dim dbConnection As ADODB.Connection
Dim rs As ADODB.Recordset
Dim dbConnectionString As String
dbConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sourcefilepath & ";Extended Properties=""csv;HDR=Yes;FMT=Delimited"""
Set dbConnection = New ADODB.Connection
dbConnection.Open dbConnectionString
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM " & sourceFileName
rs.Open strSQL, dbConnection, 3, 3
rs.Close
dbConnection.Close
I tried the code above and kept getting "could not find installable ISAM" error message.
I also tried:
dbConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sourcefilefolder & ";Extended Properties=""txt;HDR=Yes;FMT=Delimited"""
It didn't work, either.
Any advice would be appreciated. Thanks in advance.
Click on Tools > References and scroll down to:
Microsoft ? (The question is to select which connection you decide to use.)
And select:
Microsoft ADO (version you want)
and
Microsoft OLE (version you want)
I have found it also helps to select: Microsoft DAO Jet 3.6 even when I don't plan to use it as it supports several older utilties I often call on.