How to Write Select Query and Fetch Details to Excel |VBA| - excel

I have a Query Where I Need to Add Query Statement and fetch that Details to the Excel Sheet
Table name is : Student_Details
ID|Name|Course|
1 |vik |MBA |
2 |sik |CA |
3 |mil |CP |
4 |hil |MP |
query : Select * from Student_Details;
How Do I implement in Below Query
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'--- Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=ora130b-example.intra)(PORT=1534))" & _
"(CONNECT_DATA=(SERVICE_NAME=JFG))); uid=jfg_o; pwd=ure;"
'--- Open the above connection string.
con.Open (strCon)
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
con.Close
End Sub

This should make it work Taken from Link
Steps:
Set the results and Execute the Query
Print those result in a loop.
con.Open (strCon)
query = "Select * from Student_Details"
Set rs = con.Execute(query)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
Next
rs.MoveNext
Loop
rs.Close
con.Close
To directly copy data to Activesheet Use:
ActiveSheet.Range("A1").CopyFromRecordset rs

Related

Is there any way of automating certain query execution and storing the O/P of that query in a excel file?

I have around 80 queries which I execute on a daily basis for monitoring purpose. All of them being SELECT queries, we capture the mostly the counts. This is turning out to be a boring task that's just running the query and manually capturing the output in an excel file.
For example, these are my queries with their sample respective outputs:
Query#1: SELECT count(*) from table WHERE certain_condition = 'True'
OUTPUT: 985
Query#2: SELECT count(*) from another_table WHERE yet_another_condition = 'True'
OUTPUT: 365
…
Query#80: SELECT count(*) from another_table WHERE yet_another_condition = 'True'
OUTPUT: 578
My requirement is this:
Capture the output of these 80 queries and paste them in an excel file in a certain order.
In Excel, I'll already have a heading (condition) in a cell. So I want the output of each query to be mapped to a specific cell corresponding to the heading (condition).
Is there any way of automating this boring task, or am I stuck for eternity as a bot?
PS: I am using Toad for Oracle v 12.9.0.71 database
Like Tim was saying ADO is your best bet here. Lucky for you I just had to do this myself so hopefully this should work for you.
Sub SQLQuery(sqlServer As String, strDatabase As String, strQuery As String, _
exportLocation As Variant, strUserId As String, strPassword As String)
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = Nothing
Set rs = Nothing
'create the Connection and Recordset objects
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
'open the connection
conn.Open _
"Provider=SQLOLEDB;" & _
"Data Source=" & sqlServer & ";" & _
"Initial Catalog=" & strDatabase & ";" & _
"User ID=" & strUserId & ";" & _
"Password=" & strPassword & ";" & _
"Trusted_Connection=" & "True" & ";"
'execute
Set rs = conn.Execute(strQuery)
'check if data exists
If Not rs.EOF Then
'if so, copy to location
exportLocation.CopyFromRecordset rs
'close the recordset
rs.Close
End If
'clean up
conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
An example of using this subroutine:
Call SQLQuery( _
oSERVER, _
oDB, _
"SELECT count(*) from table WHERE certain_condition = 'True'", _
ThisWorkbook.Sheets("Sheet1").Cells(1, 1), _
oUSER, _
oPW)
Just for reference you will likely have to enable Microsoft ActiveX Data Objects 2.8 Library in your References for this to work.

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

How to use a loop to fill in multiple controls on a Userform?

I have the following code that looks up an ID in a data table and returns the corresponding value from other columns. Below is the code to return a single column value and post it to the TextBox/ComboBox on my form. However, I am looking to create this as a loop to post to all the 20-30 fields I have rather than repeating the code for each field.
col_no = 3 to 29
Note that my TextBox/ComboBox have varying names e.g. customer, site etc.
id_1 = OrderDisplay.id
col_no = 3
sales_order = WorksheetFunction.VLookup(id_1, Worksheets("Data").Range("A:AB"), col_no, False)
OrderDisplay.sales_order = sales_order
How can I achieve that?
Consider querying your worksheet data as a database as it seems to be tabular structure where you pass in as a parameter the specific id. In fact, this may set you up to upsize your worksheet to actual database like MS Access (Excel's sibling), SQLite, etc. where you can swap out the ADO connection string and then sheet name in SQL for database table!
Below assumes all your userform controls have the same exact name as table fields (first columns of worksheet).
Dim conn As Object, rst As Object, cmd As Object
Dim strSQL As String, id1 As Long
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Workbook.xlsm';" _
& "Extended Properties=""Excel 12.0;HDR=YES;"";"
' OPEN CONNECTION
conn.Open strConnection
' WORKBOOK QUERY
strSQL = "SELECT t.* " _
& " FROM [SheetName$] AS t" _
& " WHERE t.id = ?"
id_1 = OrderDisplay.id
' BUILD PARAMETERED QUERY
Set cmd = CreateObject("ADODB.Command")
With cmd
.ActiveConnection = conn
.CommandText = strSQL
.CommandType = adCmdText
.Parameters.Append .CreateParameter("idparam", adInteger, adParamInput, , id1)
End With
' CREATE RECORDSET
Set rst = cmd.Execute
' LOOP THROUGH RECORDSET AND FILL IN CONTROL VALUES
rst.MoveFirst
Do While Not rst.EOF
For i = 1 To rst.Fields.Count - 1
Me.Controls(rst.Fields(i).Name).Value = rst.Fields(i)
Next i
rst.MoveNext
Loop
rst.Close: conn.Close
Set conn = Nothing: Set rst = Nothing: Set cmd = Nothing

From ms access table how to paste required data form array (getrows) to excel specific ranges using vba

My below code shows no error, when run, but I don't know how to extract required/particular field values into my excel sheet.
Sub getdatafromaccesstoanarray()
Dim cn As Object 'Connection
Dim rs As Object 'Recordset
Dim vAry() As Variant 'Variant Array
Dim dbPath As String 'Database Path
Dim dbName As String 'Database Name
Dim txt As String
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
dbPath = ThisWorkbook.Path & "\"
dbName = "NewDB.accdb"
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath & dbName & ";"
rs.Open "SELECT * FROM BILLDETAILS WHERE BILLDETAILS.SN_AUTO =100;", cn
vAry = rs.GetRows()
'now when the data is copied to my array how can i paste specific values from this data to
'cells in my excel sheet
'like
'on active sheet
'[a1] = vAry(value1)
'[a2] = vAry(value3)
'[a3] = vAry(value8)
'and other values like wise
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
If there any other way to do this then please let me know.
Thanks!
If you just want to copy the recordset into the sheet you can use the CopyFromRecordset method to dump the table into the sheet by specifying the top left corner:
Range("a1").copyfromrecordset rs
If you want to put specific fields in specific positions you can loop
Do While not rs.eof
range("a2")=rs(0)
range("b2")=rs(1)
'etc....
rs.movenext
Loop

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