I want to be able to JOIN Excel tables to MsSQL tables, or to other Excel tables. I am trying to test the second case. I'm trying to get data from Excel table using the OPENROWSET. Later I will use this to join tables, but now I cant get working even this simple query.
Ciselnik1 is a Worksheet in Test.xlsx Workbook and contains a small table with header:
FK__S_HEAD | Desc
-------------------------------
ODD AM | ODD - description1
ODDZP | ODD - desc2
The follwing code is throwing the "syntax error in FROM clause" error:
Sub TestExternalSQLwithCisJoin()
Dim objConn As ADODB.Connection, objCmd As ADODB.Command, objRS As ADODB.Recordset
Dim sPath As String, sSQL As String, sConn As String
Set objConn = New ADODB.Connection
Set objCmd = New ADODB.Command
Set objRS = New ADODB.Recordset
sSQL = "SELECT * FROM OPENROWSET(""Microsoft.ACE.OLEDB.12.0"",""Database=c:\...\Test.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES"",""SELECT * FROM [Ciselnik1$]"")"
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\...\Test.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=YES"";"
Set objConn = New ADODB.Connection
'MsgBox sSQL
objConn.Open sConn
'objRS.Open sSQL, objConn, adOpenStatic, adLockBatchOptimistic, adCmdText
objConn.Execute sSQL, lngRecsAff, adExecuteNoRecords
Dim A0cell As Range
Worksheets("Test").Activate
Set A0cell = Worksheets("Test").Cells(1, 1)
A0cell.CopyFromRecordset objRS
End Sub
OPENROWSET is just not a function the Microsoft.ACE.OLEDB.12.0 provider supports.
Related
I'm trying to pull data from SQL via an ADODB recordset in VBA. I'm struggling to get results from each part of a SQL query when it contains semi-colons. Wondering if there's any way to do this without splitting my query into separate queries (to remove the semi-colon issue) and using separate recordsets for each.
See below for a simple example. When I run it, F2=1, G2=Failed - I want F2=1, G2=2.
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
' Open recordset
rs.Open "SELECT 1; SELECT 2", con
' Add data to worksheet
Range("F2").CopyFromRecordset rs
rs.NextRecordset
If rs.State > adStateClosed Then
Range("G2").CopyFromRecordset rs
Else
Range("G2").Value = "Failed"
End If
' Close connection
con.Close
End Sub
I would go about it by doing something like the below.
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim SQL_String As String
Dim SQL_Array() As String
Dim i As Integer
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
'Multiple queries
SQL_String = "SELECT 1; SELECT 2"
'Split into array
SQL_Array = Split(SQL_String, ";")
'Add data to worksheet
For i = LBound(SQL_Array) To UBound(SQL_Array)
rs.Open SQL_Array(i), con
Range("F2").Offset(0, i).CopyFromRecordset rs
Next i
' Close connection
con.Close
End Sub
Here I take the multiple queries and split them into an array that I loop over. Assuming that you want the ouptut in columns from column F and onward.
I believe you need to set the rs to the result of NextRecordset, so the code looks like this:
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
' Open recordset
rs.Open "SELECT 1; SELECT 2", con
' Add data to worksheet
Range("F2").CopyFromRecordset rs
Set rs = rs.NextRecordset
If rs.State > adStateClosed Then
Range("G2").CopyFromRecordset rs
Else
Range("G2").Value = "Failed"
End If
' Close connection
con.Close
End Sub
I am trying to automate a data pull from Access into Excel using ADO. Each week I pull in the previous weeks deals from Monday-Friday. Right now I have SQL pulling in the deals from the previous week, however the way I have it right now I would manually have to change the dates in the code each week. Is there a way to do this automatically?
Below is the code I currently have:
Sub Import()
'Declaring the necessary variables
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim dbPath As String
Dim SQL As String
Dim i As Integer
Dim var As Range
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=xxx"
'create the SQL statement to retrieve the data from the table
sSQL = "SELECT * FROM BP_Closed_Deals WHERE Start_Date between '10/21/2019' and '10/25/2019'"
'create the ADODB recordset object
Set rs = New ADODB.Recordset
'connectionString open
rs.Open sSQL, cn, adOpenForwardOnly, adLockReadOnly, adCmdText
If Not rsData.EOF Then
Sheets("Deals_2018_Copy").Range("A2").CopyFromRecordset rsData
rsData.Close
Else
rsData.Close
MsgBox "Error: No records returned", vbCritical
End If
Set rsData = Nothing
End Sub
Consider finding last Monday and Friday's date relative to today using DatePart:
sSQL = "SELECT * FROM BP_Closed_Deals "_
& "WHERE Start_Date BETWEEN Date() - (DatePart('d', Date()) - 2) - 7" _
& " AND Date() - (DatePart('d', Date()) - 2) - 3"
Hi I need to connect my Excel file to run a macro that executes select query.
My sample code is
Sub Button1_Click()
Range("A1").Value = "Hiii!"
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL, strInput As String
strCon = "Provider=MSDAORA.1;User ID=bis5151XXXXXa1;Data Source=canafpi5467qanfo.iaksedafdqwte.com;Password=iXoXXX8886s55it"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strInput = InputBox("Input Desired Name")
Sheet1.Range("B1").Value = strInput
strSQL = "select * from " & strInput & " where rownum<200"
Sheet2.Range("D1").Value = strSQL
'Added the following four lines
Set rs = CreateObject("ADODB.RECORDSET")
rs.activeconnection = cn
rs.Open strSQL
Sheet2.Range("A10").CopyFromRecordset rs
rs.Close
cn.Close
Set cn = Nothing
End Sub
=============================================
But my Database doesnt have an entry in the tnsnames.ora file. I also tried giving tns details as data source but am getting TNS failure error.
Could some one please help me to connect my excel to oracle just to run a select statement so that the value is returned to a particular cell in excel.
FYI I already have my ODBC configured.
I'm trying to run a query in an Access 2007 database from an Excel 2007 VBA script. The Access query has parameters called "Year" and "Month".
I'm trying to get the following code to work:
Sub RunMyQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim stQRY As String
Dim stCon As String
Dim cmd As New ADODB.Command
Dim prmYear As New ADODB.Parameter
Dim prmMonth As New ADODB.Parameter
dbPath = "<PATH_TO_MY_DB>"
stCon = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & dbPath & ";"
cn.Open (stCon)
cn.CursorLocation = adUseClient
Set cmd.ActiveConnection = cn
Set prmYear = cmd.CreateParameter("Year", adNumeric, adParamInput, , 2011)
Set prmMonth = cmd.CreateParameter("Month", adNumeric, adParamInput, , 5)
cmd.Parameters.Append prmYear
cmd.Parameters.Append prmMonth
cmd.CommandText = "SELECT * FROM [Month_Totals]"
cmd.CommandType = adCmdTable
Set rs = cmd.Execute
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
When I run this, the code stops on "cmd.Execute" with
Run-time error '-214217900 (80040e14)':
Syntax error in FROM clause.
What am I getting wrong?
The command text seems simple enough to me. Am I missing something there?
Am I misusing the parameters functionality of ADODB.Command? I don't think that's the problem here, because I've tried running this same script with a non-parametrized query substituted for Month_Totals, and gotten the same error.
I believe The parameters are only for use when you are using a saved query in access. I would solve your problem by moving the parameters into the SQL statment.
Change
"SELECT * FROM [Month_Totals]"
to
"SELECT * FROM [Month_Totals] WHERE Year = 2011 AND Month = 5"
The reason that this is returning an error is that command type is set to adCmdtable, but the command does not reference a table, it references an SQL string, so:
cmd.CommandType = adCmdText
Next, in order to return specific data, you need to include a WHERE clause, with field names in the correct order for the parameters:
cmd.CommandText = "SELECT * FROM [Month_Totals] Where [Year]=? AND [Month]=?"
i want to allow the user to upload xls file with 9 columns and unlimited number of rows.
i will run over everyline and insert the data to the db
how do i read the xls file?
You can read the XLS by opening an ADO recordset which pulls in the spreadsheet's data.
This example reads data from a spreadsheet named Billing Summary which includes column names in the first row..
Public Sub ReadSpreadsheet()
Const cstrFolder As String = "C:\Access\webforums"
Const cstrFile As String = "ExampleFinance.xls"
Dim strConnect As String
Dim strSql As String
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
cstrFolder & Chr(92) & cstrFile & _
";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strConnect
strSql = "SELECT * FROM [Billing Summary$] WHERE SomeField Is Not Null;"
rs.Open strSql, cn
Do While Not rs.EOF
'* do something with each row of data *'
'Debug.Print rs!SomeField '
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If that particular connection string doesn't work for you, look at other examples of Excel connection strings at Connection strings for Excel
Edit: That example works in Access. But you said ASP. I think it will work there, too, if you drop the data types from the variable and constant declarations: Dim strSql instead of Dim strSql As String
Example of using an SQL statement to update Access from Excel.
Set cn = CreateObject("ADODB.Connection")
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\docs\dbto.mdb"
cn.Open scn
sSQL = "SELECT * INTO NewTable FROM "
sSQL = sSQL & "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Docs\From.xls].[Sheet1$]"
cn.Execute sSQL, recs
MsgBox recs
In C#, I had to load an excel spreadsheet to a DataSet - this got me there...
Code Project Example
I used Option 1 - the Preferred method! Hope this helps...
Mike