It is something like complicated when you want to export reports from reporting objects like List view in VB6. In fact Excel object has provided a way to directly export contents of a table into Excel format in a quick manner using DAO or ADO connection.
To illustrate this we need,
- A DAO, ADO database connection
- Excel Objects
- Loop to print column heading
Connection
You may be familiar with the database connections in VB6, the following is an example of ADO data connection.
Dim adodb_db As New ADODB.Connection
Dim adodb_rs As New ADODB.Recordset
adodb_db.ConnectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\emp.mdb;Persist Security Info=False”
adodb_db.Open
adodb_rs.Open “select * from Accounts “, adodb_db, adOpenKeyset
The excel objects
The excel objects are required to create a new Excel file in order to export the rows of a table.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
The columns
The CopyFromRecordset of Excel object didn’t fetch columns, so we do it manually as follows.
If adodb_rs.RecordCount > 0 Then
adodb_rs.MoveFirst
adodb_rs.MoveNext
adodb_rs.MoveLast
adodb_rs.MoveFirst
‘Start a new workbook in Excel
Set oExcel = CreateObject(“Excel.Application”)
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
For c = 0 To adodb_rs.Fields.count – 1
oBook.Worksheets(“Sheet1”).Cells(1, c + 1) = adodb_rs.Fields(c).Name
Next c
End if
Copying the rows to Excel
The Excel Worksheet object’s CopyFromRecordset help you to copy records to excel rows, all you need to specify the cell range.
oBook.Worksheets(“Sheet1”).Range(“A2”).CopyFromRecordset adodb_rs
The complete code
Here is the complete code
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim adodb_db As New ADODB.Connection
Dim adodb_rs As New ADODB.Recordset
adodb_db.ConnectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\SherPharma\SIGMA1819.mdb;Persist Security Info=False”
adodb_db.Open
adodb_rs.Open “select * from Account_Transactions “, adodb_db, adOpenKeyset
‘Set rs = MedicalShop.OpenRecordset(“select entryno,itemname,total from Sales_Particulars “)
If adodb_rs.RecordCount > 0 Then
adodb_rs.MoveFirst
adodb_rs.MoveNext
adodb_rs.MoveLast
adodb_rs.MoveFirst
‘Start a new workbook in Excel
Set oExcel = CreateObject(“Excel.Application”)
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
For c = 0 To adodb_rs.Fields.count – 1
oBook.Worksheets(“Sheet1”).Cells(1, c + 1) = adodb_rs.Fields(c).Name
Next c
oBook.Worksheets(“Sheet1”).Range(“A2”).CopyFromRecordset adodb_rs
oExcel.Visible = vbTrue
End If
Like this:
Like Loading...