VBA code to connect to Oracle Data base to run SQL statements - excel

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.

Related

Import data from Access (mdb) file to Excel with VBA

I lost my working code before I wrote to get data from .mdb file to Excel with VBA. Now, I did not find the true way to get data to excel. Here is the my code to import data;
Sub importAccessdata()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sQRY As String
Dim strFilePath As String
strFilePath = "D:\00 - DENEME\Deneme_Model_v0.mdb"
'Replace the ‘DatabaseFolder’ and ‘myDB.accdb’ with your DB path and DB name
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & strFilePath & ";"
sQRY = "SELECT * FROM Connectivity"
'Replace ‘tblData’ with your Access DB Table name or Query name from which you want to download the data
With rs
.CursorLocation = adUseClient
.Open Source:=sQRY, ActiveConnection:=cnn, CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, Options:=adCmdText
End With
Application.ScreenUpdating = False
Sheet1.Range(“A1”).CopyFromRecordset rs
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
I got Run-Time Error 424 when I were running to code, I got error in "Sheet1.Range(“A1”).CopyFromRecordset rs" part of code.
I just want to get data from another Software output to use in Excel easily. My .mdb file can be seen here
Whats wrong I don't know. Also I have Sheet1 worksheet in my Excel file.

Catastrophic Failure EXCEL VBA - error '-2147418113 (8000ffff)'

I am struggling to find relevant information on the
'run-time error '-2147418113 (8000ffff)' - Catastrophic Failure'
I am experiencing.
Sub GenerateAIA_Click()
Dim SQL_query, SQL_syntax, DB_path, setting_conn As String
Dim conn As New ADODB.Connection
Dim query_rslt As New ADODB.Recordset
Dim mth, mth_yr As Variant
Dim dt As Date
Dim i, bol As Integer
Dim temp1, temp2 As Variant
dt = Sheets("Main").Range("C4")
mth_yr = MonthName(Month(Sheets("Main").Range("I12")), False) & " " & Year(Sheets("Main").Range("I12"))
ThisWorkbook.Sheets("AIA").Select
DB_path = ThisWorkbook.FullName 'Refering the same workbook as Data Source
setting_conn = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DB_path & ";HDR=Yes';"
conn.Open setting_conn
SQL_syntax = "SELECT * FROM [Setup$]" 'Your SQL Statement (Table Name= Sheet Name=[Sheet1$])
query_rslt.Open SQL_syntax, conn
I have also noticed that this error is shown on the line
conn.Open setting_conn
I use excel 2016 and also my file format .xlsm
Anyone have idea why is this happening?
It seems your connection string has a problem.
Here's how I got it to work:
(First make sure to add a reference to the Microsoft Active-X Data Objects Library)
Sub test()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\PC\test.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=NO"";"
conn.Open
rs.Open "SELECT * FROM [Sheet1$]", conn
If Not rs.EOF Then
MsgBox rs(0) ' display the value of the first field in the first row
Else
MsgBox "No records found."
End If
rs.Close
conn.Close
End Sub
So take my example, change the filename to your XLSM file, and the sheet name to your sheet name (with a $ added to the end of it)
If your sheet has header names in the first now, use HDR=Yes, and if not, HDR=No
or you can change display resolution for your monitor

Retrieve all of query containing semi-colons

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

Error when running a parameter query from access 2007 in excel vba

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]=?"

asp and ms-access db - how to import data from xls file

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

Resources