database to excel manipulate data
I am trying to get data from a database and present it in excel in a predictable way -- i want to be able to assign specific fields from the database to specific cells in the excel spreadsheet ...; i would also like to format the results, i.e. change the database column names into something more reportable.
ideally, i would like to be able to refer to results from the query as variables so that I can put them in specific places and perform computations on the results before being printed to the spreadsheet.
here is the code I am using:
Sub pubConn()
Dim objConn As ADODB.connection
Dim objRS As ADODB.Recordset
Dim stSQL As String
Set objConn = New ADODB.connection
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
Set ws = ThisWorkbook.Worksheets("intro")
objConn.Open "Driver={SQL Server};Provider=SQLOLEDB;data source=SQLSERVER;database=DB;Uid=uid;Pwd=pwd"
stSQL = "SELECT * FROM table"
objRS.Open stSQL, objConn
For iCols = 0 To objRS.Fields.Count - 1
ws.Cells(1, iCols + 1).Value = objRS.Fields(iCols).Name
Next
ws.Range(ws.Cells(1, 1), _
ws.Cells(1, objRS.Fields.Count)).Font.Bold = True
ws.Range("A2").CopyFromRecordset objRS
End Sub
this is a block return though and does not allow me to format specific results from the query in the spreadsheet -- it essentially dumps the data.
thanks.
|