Solved

MS Access OutputTo Report using filter string

Posted on 2010-11-15
28
597 Views
Last Modified: 2012-05-10
Hi there,

I am trying to create an outputto report function for my database. The report currently filters propery when using
DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere but I would like to be able to output this to an excel spreadsheet with the filtered items being displayed.  I have tried using the DoCmd.OutputTo acOutputReport, "reportName", ... format but it doesn't filter at all.

Your help is much appreciated in advance.
0
Comment
Question by:databarracks
  • 16
  • 11
28 Comments
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

Create a select query called SQLOutput - does not matter what the SQL is.

...
DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere
CurrentDb.QueryDefs("SQLOutput ").SQL = Reports("rptFilter").SQL
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput ", "C:\xyz.xls"
...

This will export the filtered report data shown in Print Preview to excel file C:\xyz.xls

Regards,

Bill
0
 

Author Comment

by:databarracks
Comment Utility
Could kindly explain what you mean exactly by "Create a select query called SQLOutput - does not matter what the SQL is."?
0
 

Author Comment

by:databarracks
Comment Utility
I have copied the code into mine and can confirm it is filtering the report into a preview mode. But I do have a run-time error '2465' "Application-defined or object-defined error"?
0
 
LVL 74

Expert Comment

by:Jeffrey Coachman
Comment Utility
This could be many things...
Then can you please post the code you are using?
0
 

Author Comment

by:databarracks
Comment Utility
Here you go as requested.
Private Sub Command100_Click()
    'Purpose:   Build up the criteria string form the non-blank search boxes, and apply to the form's Filter.
    'Notes:     1. We tack " AND " on the end of each condition so you can easily add more search boxes; _
                        we remove the trailing " AND " at the end.
    '           2. The date range works like this: _
                        Both dates      = only dates between (both inclusive. _
                        Start date only = all dates from this one onwards; _
                        End date only   = all dates up to (and including this one).
    Dim strWhere As String                  'The criteria string.
    Dim lngLen As Long                      'Length of the criteria string to append to.
    Const conJetDate = "\#mm\/dd\/yyyy\#"   'The format expected for dates in a JET query string.
    
    '***********************************************************************
    'Look at each search box, and build up the criteria string from the non-blank ones.
    '***********************************************************************
    'Text field example. Use quotes around the value in the string.
    If Not IsNull(Me.txtFilterCity) Then
        strWhere = strWhere & "([Country] Like ""*" & Me.txtFilterCity & "*"") AND "
    End If
    
       'Text field example. Use quotes around the value in the string.
    If Not IsNull(Me.txtRating) Then
        strWhere = strWhere & "([Satisfaction] Like ""*" & Me.txtRating & "*"") AND "
    End If
    
        'Text sage code example. Use quotes around the value in the string.
    If Not IsNull(Me.txtSage) Then
        strWhere = strWhere & "([ACCOUNT_REF] Like ""*" & Me.txtSage & "*"") AND "
    End If
    
         'Text Account Manager example. Use quotes around the value in the string.
    If Not IsNull(Me.txtEmployee) Then
        strWhere = strWhere & "([AccountManager] Like ""*" & Me.txtEmployee & "*"") AND "
    End If
    
    
    'Contract Length Search
     If Not IsNull(Me.txtContractLength) Then
        strWhere = strWhere & "([ContractLength] Like  ""*" & Me.txtContractLength & "*"") AND "
    End If
    
    'Contract Length Search
     If Not IsNull(Me.txtAddress) Then
        strWhere = strWhere & "([Address] Like  ""*" & Me.txtAddress & "*"") AND "
    End If
    
    'First Name of Customer Contact
     If Not IsNull(Me.txtFirstName) Then
        strWhere = strWhere & "([FirstName] Like  ""*" & Me.txtFirstName & "*"") AND "
    End If
    
    'Another text field example. Use Like to find anywhere in the field.
    If Not IsNull(Me.txtFilterMainName) Then
        strWhere = strWhere & "([CompanyName] Like ""*" & Me.txtFilterMainName & "*"") AND "
    End If
    
    'Yes/No field and combo example. If combo is blank or contains "ALL", we do nothing.
    If Me.cboFilterIsCorporate = -1 Then
        strWhere = strWhere & "([Reseller] = True) AND "
    ElseIf Me.cboFilterIsCorporate = 0 Then
        strWhere = strWhere & "([Reseller] = False) AND "
    'ElseIf Me.cboFilterIsCorporate = 1 Then
        'strWhere = strWhere & "([Reseller] = Null) AND "
    End If
    
    'Date field example. Use the format string to add the # delimiters and get the right international format.
    If Not IsNull(Me.txtStartDate) Then
        strWhere = strWhere & "([Commencement] >= " & Format(Me.txtStartDate, conJetDate) & ") AND "
    End If
    
    'Another date field example. Use "less than the next day" since this field has times as well as dates.
    If Not IsNull(Me.txtEndDate) Then   'Less than the next day.
        strWhere = strWhere & "([Commencement] < " & Format(Me.txtEndDate + 1, conJetDate) & ") AND "
    End If
    
     'Date field example. Use the format string to add the # delimiters and get the right international format.
    If Not IsNull(Me.txtLastInvoice) Then
        strWhere = strWhere & "([LastInvoiceAmount] >= " & Format(Me.txtLastInvoice) & ") AND "
    End If
    
    'Another date field example. Use "less than the next day" since this field has times as well as dates.
    If Not IsNull(Me.txtLastInvoice2) Then   'Less than the next day.
        strWhere = strWhere & "([LastInvoiceAmount] <= " & Format(Me.txtLastInvoice2) & ") AND "
    End If
    

    '***********************************************************************
    'Chop off the trailing " AND ", and use the string as the form's Filter.
    '***********************************************************************
    'See if the string has more than 5 characters (a trailng " AND ") to remove.
    lngLen = Len(strWhere) - 5
    If lngLen <= 0 Then     'Nah: there was nothing in the string.
        MsgBox "No criteria", vbInformation, "Nothing to do."
    Else                    'Yep: there is something there, so remove the " AND " at the end.
        strWhere = Left$(strWhere, lngLen)
        'For debugging, remove the leading quote on the next line. Prints to Immediate Window (Ctrl+G).
        'Debug.Print strWhere
        
        'Finally, apply the string as the form's Filter.
        Me.Filter = strWhere
        Me.FilterOn = True
    End If
    DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere
    CurrentDb.QueryDefs("SQLOutput ").SQL = Reports("rptFilter").SQL
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput ", "C:\xyz.xls"

End Sub

Open in new window

0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

Just make a select query.  Select one field from any table and save the query with the name SQLOutput.  We need a querydef to output.  We change the sql in code.

Also, chege the line
CurrentDb.QueryDefs("SQLOutput ").SQL = Reports("rptFilter").SQL

to (remove the space after "SQLOutput "
CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").SQL

Regards,

Bill
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Also remove the space in this line:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput ", "C:\xyz.xls"

to

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput", "C:\xyz.xls"
0
 

Author Comment

by:databarracks
Comment Utility
Hi Bill,

I have tried that and I got the same error? Could you give me the exact code after the End If because I currently have the attached code. Not too sure where  I should put your suggested code


DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere

CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").SQL

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput ", "C:\xyz.xls"

Open in new window

0
 

Author Comment

by:databarracks
Comment Utility
Ok I have removed the space in both and the same error unfortunately
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Did you create the query?
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

You only need to add 2 lines of code.  Check your original code.

Does the report show and do you get errors in it?

If not AND if you have created the query named SQLOutput then you would need to put the 2 lines of code after your line of code:
DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere

add these 2 lines:

CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").SQL
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput", "C:\xyz.xls"

Bill
0
 

Author Comment

by:databarracks
Comment Utility
Yes and I have and named it SQLOutput.
0
 

Author Comment

by:databarracks
Comment Utility
Yes the report shows perfectly fine, and once I have selected to end the debug I can convert it to an excel file, it is just that other users may not know what to do when the error appears.
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

Please determine which line of code is giving you the error.

Comment out the first line then the second and see if either gives the error.

Bill
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:databarracks
Comment Utility
I have commented out 'CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").SQL' and it seems to be working fine. No errors popping up, however the .xls report doesn't appear to be filtered and is showing all records.
0
 

Author Comment

by:databarracks
Comment Utility
Would this be caused by my SQLOutput query?
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

Try this slight change to see if the error corrects:

Replace
CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").SQL

with
CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").recordsource

If you still get the error post the SQL for the query SQLOutput

Bill
0
 

Author Comment

by:databarracks
Comment Utility
Unfortunately the error is persisting. The new error is 'Invalid SQL statement; expected 'DELETE', 'INSERT','PROCEDURE','SELECT', or 'UPDATE'. The SQL for my query is attached.
SELECT Company.ID, Company.CompanyName, Company.ContractExpiryDate, Company.FirstName, Company.[E-mail], Company.ContractLength, Company.AccountManager, Company.Commencement, Company.LastInvoiceAmount
FROM Company;

Open in new window

0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

OK.  The query is correct so I susect you have an incorrect filter that the report passes but the query fails.

Replace this line:
CurrentDb.QueryDefs("SQLOutput").SQL = Reports("rptFilter").recordsource

with these 2 lines:
debug.print Reports("rptFilter").recordsource
stop

The code will stop and the debug window will show the SQL for the filtered report.  Post this code.

Bill
0
 

Author Comment

by:databarracks
Comment Utility
My immediate window shows 'Company'
0
 

Author Comment

by:databarracks
Comment Utility
This is what I currently have for my code.
DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere
    Debug.Print Reports("rptFilter").RecordSource
    Stop
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput", "C:\xyz.xls"

Open in new window

0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,
Replace
Debug.Print Reports("rptFilter").RecordSource
With
Debug.Print strWhere

This will aloow up to look at the where clause.

Bill
0
 

Author Comment

by:databarracks
Comment Utility
Yes I ahve changed this and had a filter for first name called mark and received this:

([FirstName] Like  "*mark*")
0
 
LVL 14

Expert Comment

by:Bill Ross
Comment Utility
Hi,

Lastly let's look at the reports SQL statement.

Debug.Print Reports("rptFilter").SQL

Bill
0
 

Author Comment

by:databarracks
Comment Utility
I replaced 'Debug.Print strWhere' with 'Debug.Print Reports("rptFilter").SQL' and got an Application-defined or object-defined error
0
 
LVL 14

Accepted Solution

by:
Bill Ross earned 125 total points
Comment Utility
Hi,

OK.  We can make a correct SQL statement from the strWhere.  Replace the last lines in your code with:

DoCmd.OpenReport "rptFilter", acViewPreview, , strWhere
CurrentDb.QueryDefs("SQLOutput").SQL ="SELECT * FROM Company WHERE " & strWhere
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SQLOutput", "C:\xyz.xls"

Bill


0
 

Author Comment

by:databarracks
Comment Utility
Hi Bill,

That has worked perfectly Bill. Thank you very much for your help and patience with this issue,  it has been much appreciated.
0
 

Author Closing Comment

by:databarracks
Comment Utility
Very helpful with my problem.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Introduction This Article briefly covers methods of calculating the NPV and IRR variants in Excel as well as the limitations in calculating and interpreting IRR results. Paraphrasing Richard Shockley, author of my favourite finance reference tex…
As with any other System Center product, the installation for the Authoring Tool can be quite a pain sometimes. This article serves to help you avoid making these mistakes and hopefully save you a ton of time on troubleshooting :)  Step 1: Make sur…
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now