Excel Object .CopyFromRecordset method (and ADODB.Recordset.Filters)
Posted on 2002-05-24
I have a little probel with the CopyFromRecordset method of an Excel object.
Baiscally All I want to do is return all from a table and send to Excel object, usually this is very simple but the twist is that I wish to filter the recordset first. And when I so the CopyFromRecordset seems to disregard the filter and send the whole recordset rather than the filtered records..
If this is not at all possible I guess I'd ashve to somehow fabricate a third recordset and populate that with the records adhering to the filter then pass the third recordset through CopyFromRecordset. But again I'd need help with that.
The code below is the method I use.
Have a look see what you can come up with..
Private Sub ExportReport(DateFrom As String, DateTo As String)
Dim RS As ADODB.Recordset
Dim RS2 As ADODB.Recordset
Dim strSQL As String
Dim clnRS As ADODB.Recordset
'Excel application objects
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
'Grab all sites on DB
Set RS = OpenRecordSet("Select Distinct(ProductGroup) From tblagentProduct Order by ProductGroup asc")
If RS.RecordCount > 0 Then
'should be data so log error
Log_Error "No Product Groups Found in TBLAgentProduct", "frmCrossSales-ExportReport"
'For each site grab all info
strSQL = "exec sp_XSalesReport '" & DateFrom & "', '" & DateTo & "'"
Set RS2 = OpenRecordSet(strSQL)
While Not RS.EOF
RS2.Filter = "ProductGroup = " & RS!ProductGroup
Set clnRS = RS2.Clone
Set xlSheet = xlBook.Worksheets.Add
'Name it by Site Name from DB
xlSheet.Name = RS!ProductGroup
'Make visible and give user control
xlApp.Visible = True
xlApp.UserControl = False
'Set titkes for coloumns.(unable to make BOLD for some reason
xlSheet.Cells(1, 1) = "Method Of Sale"
xlSheet.Cells(1, 2) = "Product Sold"
xlSheet.Cells(1, 3) = "Outcome"
xlSheet.Cells(1, 4) = "Roll Number"
xlSheet.Cells(1, 5) = "Amount"
xlSheet.Cells(1, 6) = "Application Decision"
'Main import function that imports data from recordset
xlSheet.Cells(4, 1).CopyFromRecordset RS2
'Set coloumn widths and tidy up.
.Selection.ColumnWidth = 25
'RS2.Filter = adFilterNone
'Give User COntrol
xlApp.UserControl = True
'Hides the first 3 default worksheest created automatically by the Excel app.
'Couldnt find a away to remove those without user interaction so I'm just hiding them..<CDS>
On Error Resume Next
xlApp.Worksheets("Sheet1").Visible = False
xlApp.Worksheets("Sheet2").Visible = False
xlApp.Worksheets("Sheet3").Visible = False
Set RS = Nothing
Set RS2 = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
Well thats it..
As i'm in a good mood successfull source without too much change will result in a 50points bonus..