Monday, August 18, 2008

Connecting to a SQL Database from Excel

First of all - WHY would anyone download data directly from a SQL database into an Excel spreadsheet on an automated basis? The simple fact that I am writing this indicates that someone needed it....but I think the idea is just silly.

1.: Create the necessary trigger (button) and double-click in design mode to start entering code.

2. Paste the following code into the beginning of the sub routine.
Dim dbs As Database
Dim rs As Recordset
Dim vtSql As String
Dim numberOfRows As Integer
ThisWorkbook.Activate

3. In my case, I read from the data in rows A12 through A30 and fed this into the SQL statement
''Open the database
For i = 12 To 30
'Get value from user
a = Me.Range("A" & i, "A" & i).Value
'If value is blank, skip processing
If a = "" Then GoTo 100
'All the fun database stuff
Set dbs = OpenDatabase("ENTER NAME OF OBDC DATA SOURCE NAME HERE", False, True, "ODBC;Regional=Yes")vtSql = "ENTER SQL STATEMENT HERE"
Set rs = dbs.OpenRecordset(vtSql)
'Drop data back onto the spreadsheet
Me.Range("B" & i).CopyFromRecordset rs
dbs.Close
Set dbs = Nothing
Set rs = Nothing
100
Next i

No comments: