Parameters in Excel External Data Union Query - sql

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

Related

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

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")

VBA LOOP in ORACLE SQL

I was trying to write a VBA to run a query assigned to MySQL only when the HCR_DM.HCR_DM_FACT table is fully loaded. I'm using the count of distinct source in that table to decide if it is fully loaded.
When I was running the Macro below, I got an error message for the Do While line, saying that Object doesn't support this property or method.
I'm quite new to VBA, and I couldn't figure out what need to be adjusted. Can some one help me with this?
Thanks!
Const CNSTR = "Provider = OraOLEDB.Oracle; Data Source =CSDPRO; ODBC;DRIVER={Oracle ODBC Driver};SERVER=CSDPRO;User ID=HCR_SANDBOX;password=******"
Sub FillWithSQLData(strSQL As String, wkSht As String)
' Given a SQL query and worksheet, fills the worksheet with a data dump of the SQL query results
' Define variables
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql_count As String
' Set variables
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Connect to SQL Server
With cn
.ConnectionString = CNSTR
.Open
End With
' Query SQL Server and return results as a data dump in cell A2 of the specified worksheet
With rs
.ActiveConnection = cn
sql_count = "select count( distinct a.src_table) from hcr_dm.hcr_dm_fact a"
Set rf = cn.Execute(sql_count)
Do While rf.Fields.Value = 8
.Open strSQL
Loop
Worksheets(wkSht).Range("A2").CopyFromRecordset rs
.Close
End With
' Close connection
cn.Close
Set rs = Nothing
Set Conn = Nothing
End Sub
Sub Refresh()
' Define SQL query
Dim mySQL As String
mySQL = "select a.oracle_fin_company_id || ' - ' || a.oracle_fin_company_desc as COMPANY " & _
"From hcr_dm.legal_entity_summary a " & _
"where a.Company_Header = 'Filed'"
' Choose worksheet where results should be displayed
Dim myWkSht As String
myWkSht = "Sheet1"
' Call connection sub
Call FillWithSQLData(mySQL, myWkSht)
End Sub
You're not selecting a field. The lines
Set rf = cn.Execute(sql_count)
Do While rf.Fields.Value = 8
Should probably be
Set rs = cn.Execute(sql_count)
Do While rs.Fields(0).Value = 8
Also, note the typo in that you declared rs but you're filling rf with the Recordset.
I recommend you use the Option Explicit statement to help find these. You can read more about it here.

Excel 2010 to Sql Server 2008 Insert Statment

I am going from Excel to Sql. I have the connection established. I can create a simple select statment and obtain values from a table in Sql into Excel. Now, I want to go the other way. I am trying to insert a value from excel into Sql. I keep getting a "Operation not allowed when object is closed" error # 3704. Below is my code.
Option Explicit
Private Conn As ADODB.Connection
Private Sub CommandButton1_Click()
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
'This will create the string to connect.
sConnString = "Driver={SQL Server};Data Source=**;Initial Catalog = **;Trusted_Connection =yes;"
'Create Connection and the Recordset Objects.
Set Conn = New ADODB.Connection
Set rs = New ADODB.Recordset
'Open the Connection in Order to Execute.
Conn.Open sConnString
Set rs = Conn.Execute("insert into TestTable(TestColumn) Values('50');")
'Check for the Data.
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
'Close Connection
rs.Close
Else
MsgBox "Error: No Records Returned.", vbCritical
End If
'Clean
If CBool(Conn.State And adStateOpen) Then Conn.Close
Set Conn = Nothing
Set rs = Nothing
End Sub
How do I properly execute this statement? As I said earlier the select statment worked fine. all I did was
("Select * From KpiSetupOee;")
Any thoughts? Thank you for your time
An INSERT statement doesn't return any records, so why are you trying to assign its results to a recordset? Change this line:
Set rs = Conn.Execute("insert into TestTable(TestColumn) Values('50');")
to just execute:
Conn.Execute("insert into TestTable(TestColumn) Values('50');")
Then clean up your code to get rid of unneeded recordset references.

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