Last Update: 06 January 2012
Product: StarSQL
Version: v5.x
Article ID: SQV00SQ055
This document describes how to use the StarSQL software, Microsoft Visual Basic for Applications (VBA), and ADO to automatically populate an Excel spreadsheet with DB2 data. Similar VBA applications can be used with the other members of the Microsoft Office Suite such as Word and Access, as well as other applications that support VBA.
The Visual Basic for Applications programming language is similar, but not identical, to Visual Basic. There are several StarQuest tech notes related to using StarSQL with Visual Basic that may be used to provide additional examples.
The example below has been tested with Excel from Office 2007 and Office 2010.
Sub Auto_Open()
Dim cnn As ADODB.Connection
Dim rst As ADODB.RecordsetSet cnn = New ADODB.Connection
Set rst = New ADODB.Recordsetcnn.Open "MYDSN", "myuser", "mypassword"
rst.ActiveConnection = cnn
rst.Source = "SELECT * FROM MYTABLE"
rst.Open' Clear the existing data from the spreadsheet
ActiveSheet.Cells.Clear' Copy field names to the first row of the worksheet
fldCount = rst.Fields.Count
For iCol = 1 To fldCount
ActiveSheet.Cells(1, iCol).Value = rst.Fields(iCol - 1).Name
Next
' Copy the recordset to the worksheet, starting in cell A2
ActiveSheet.Cells(2, 1).CopyFromRecordset rst
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = NothingEnd Sub
The information in technical documents comes without any warranty or applicability for a specific purpose. The author(s) or distributor(s) will not accept responsibility for any damage incurred directly or indirectly through use of the information contained in these documents. The instructions may need to be modified to be appropriate for the hardware and software that has been installed and configured within a particular organization. The information in technical documents should be considered only as an example and may include information from various sources, including IBM, Microsoft, and other organizations.