Run Excel SQL on Existing Sheet - Invalid Sheet/Table - sql

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

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.

On click I'm getting error "Argument is not optional"

I have tried the following code in Excel. It is connecting successfully. I want to get input values from user. To get value from user, I have used Range.Value("N3") and Range.Value("N4").
It works fine without getting value in that way. But when I add value on excel sheet and click the button to fetch records,
it gives me the error
"Argument is not optional"
If someone here can check this?
Here is the code :
Private Sub CommandButton1_Click()
Dim mon As String
Dim yea As String
mon = Range.Value("N3")
yea = Range.Value("N4")
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=inFlow;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "exec dbo.ReportTotalCompanyMonthlySales ' & yea & ',' & mon&'"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
End Sub
Try this:
mon = Range("N3").Value
instead of
mon = Range.Value("N3")

Parameters in Excel External Data Union Query

I have two queries that pull data from SQL Server into Excel. Both work perfectly fine. I tried to Union them together and pass in a parameter as a date, and now nothing works. Here's a link to an article that describes how to use Microsoft Query, and pass in a parameter.
http://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/
All I want to do is get this working with a Union Query. Is that possible? Or, do I need a VBA solution to achieve this. I'm sure it's do-able, I just don't know exactly how to do it. I'd appreciate any suggestions.
Thanks!
Thanks everyone. I ended up doing it in VBA.
Sub ImportFromDB()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=SERVER_NAME;INITIAL CATALOG=Data_Base;"
'Use an integrated login.
strConn = strConn & "Trusted_Connection=Yes;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
Set sht = Worksheets("Impact Analysis")
With sht
.Range("N:U").ClearContents
.Range("N1").Resize(1, 8).Value = Array("CONTACT_ID", "CATEGORY", "COMPANY_CODE", "CUSTOMER_NO", "SECTOR", "DES", "ASOFDATE", "BALANCE")
Set rw = .Rows(2)
End With
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM MY_TABLE"
' Copy the records into cell A1 on Sheet1.
Worksheets("Impact Analysis").Range("N2").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

runtime error '-2147217900' (80040e14)': automation error using where in the sql query from excel vba

I am trying to connect to my sqlserver express 2005 from excel vba using the following (copied from some forum routine as i am not very into databases). It works perfect. As soon as I use WHERE in the sqlquery variable (already verified quotes double and single) i get
runtime error '-2147217900' (80040e14)':
automation error
Similar routine that work pulling data from other people same thing. I appreciate deeply your help
Thanks
Sub ConnectTEST()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim sqlquery As String
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
sqlquery = "SELECT * FROM [Logisuite].[dbo].[EoWebStatus]"
'Connect to the Pubs database on the local server.
strConn = strConn & "Server=SERVITRANSMAIn\SQLEXPRESS;Database=logisuite;Trusted_Connection=True;"
'Use an integrated login.
strConn = strConn & "INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open sqlquery
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

Proper syntax for exec of SQL Server stored procedure from within Excel 2007

Let's skip to the command text box on the definitions tab of the connection properties.... my command type is SQL.
I can execute spDuplicatesAnalysis from within SSMS. I have tried a numbee things with no luck, including ...
exec spDuplicatesAnalysis
dbo.spDuplicatesAnalysis
So how should the actual command txt read ?
Thx!
Calling stored procedures from Excel VBA
Open a new Excel workbook
Name one of the tabs "Data" (or change the code below)
Open the VB Editor (Alt+F11)
Add a new module
Set a reference to Microsoft ActiveX Data Objects (choose highest version number available)
Add the following code to your module
Sub ExecStoredProcedureFromExcelVBA()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connectString As String
Dim custState As String
Dim tgt As Worksheet
Set tgt = ThisWorkbook.Sheets("Data")
custState = "TX"
' Clear the target worksheet
tgt.UsedRange.Clear
' Set the connection string
connectString = "Provider=SQLOLEDB;Data Source=.;" & _
" Initial Catalog=Sandbox;Integrated Security = SSPI"
' Create the adodb objects
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute the stored procedure
cn.Open connectString
cn.spGetCustomersForState custState, rs
' Check for results
If rs.state = 1 Then
If Not rs.EOF Then
' Write the contents of the recordset to our target
tgt.Range("a1").CopyFromRecordset rs
rs.Close
End If
End If
' Clean up after ourselves
If CBool(cn.state And adStateOpen) Then cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub
Modify the module to reference the database, stored procedure, and parameters you want to work with
Run the code