11/03/2011 01:25 by KCornell
Open Excel, then type a list of names in one column and ages in an adjacent column. Label the tops of these columns with the text "Names" and "Ages." This step creates a database of sample data for your SQL program to fetch. You can create a table with different data if you'd like.
Drag a selection region around the table, then type "MyTable" in the text box to the left of the formula bar. This creates a range name for the sample data, which your program will need to access the data.
Save the file as "C:\MyDatabase.xlsx," then close the file.
Press "Control," followed by "N" to create a new spreadsheet. You'll store your SQL program in this sheet.
Press "Alt," followed by "F11" to enter the VB development environment, commonly abbreviated as the "IDE." Developers write and sometimes execute VB programs in this IDE.
Click the "Insert" menu, then click the "Module" item. This action creates a new code window for you to enter your SQL program listing.
Click the "Tools" menu heading, then click "References." Place a check in the checkbox labeled "Microsoft ActiveX Data Objects." This action makes visible the database objects that Excel needs to run the SQL query.
Paste the following program into the new code window.
Sub sqlVBAExample()
Dim objConnection As ADODB.Connection
Dim objRecSet As ADODB.Recordset
Set objConnection = New ADODB.Connection
objConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myDatabase.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
objConnection.Open
Set objRecSet = New ADODB.Recordset
objRecSet.ActiveConnection = objConnection
objRecSet.Source = "Select * From myTable"
objRecSet.Open
Range("D10").CopyFromRecordset objRecSet
objRecSet.Close
objConnection.Close
Set objRecSet = Nothing
Set objConnection = Nothing
End Sub
Click one of the program's statements, then press "F5" to run the program.
Press "Alt," and then "F11" to return to the Excel spreadsheet. The spreadsheet will display the results of the SQL connection that your program established. The results include the database table you created earlier.
A: Launch Microsoft Visual Basic Express and click "New Project..." on the left pane of your screen then select "Console Application." Click "O...(more)
A: Connect to the Oracle SQL*Plus, click "Start," "All Programs," then click "SQL *Plus." Log onto the Oracle SQL*Plus Dialog Box, enter "Use...(more)
A: Download a free SQL program editor. RazorSQL is but one of the many free options available (see References). Unless you've previously done a...(more)
A: Type "Option Explicit" on your code's first line. This forces explicit declaration of every variable in your program. Type "Dim objConnectio...(more)
A: Log into the SQL server. Type the statement "DATEDIFF(day, 2010-01-01, 2012-03-02)" to calculate the number of days between January 01, 20...(more)
Added Successfully!
×Voted Successfully!
×You can't vote for yourself
×You can't choose your own answer
×