Search code examples
ms-accessvbams-access-2016

Detecting the invoking object from within a report


Is there some way I can detect, from within a report, which form invoked the report?

I have a form for selecting several criteria which are used to build the WhereCondition for various reports. In the report On Load, I test for the calling form being open. If it is open, I grab the selection criteria for display in the report header. If it isn't open, I display things like "Species: All" instead of, for example "Species: Blue-tailed damselfly". That works ok in this particular case but it feels a bit flaky. I would prefer to know what it was that invoked the report, in case in some future more complex system, a report could be invoked from different places. I know that a parent form is available from within a subform but that doesn't apply in this situation.


Solution

  • You have a form where the user selects the criteria used to build the WhereCondition which is used to filter the report. Do not ask the report to re-examine the form criteria in order to generate the appropriate header for itself. Build your header string in the same form procedure which builds the WhereCondition. Then pass that string as OpenArgs when you call OpenReport.

    For example, if no restriction is placed on species:

    strHeader = "Species: All"
    

    Or for the selected species:

    strHeader = "Species: Blue-tailed damselfly"
    

    Then pass strHeader when you open the report:

    DoCmd.OpenReport ReportName:="YourReport", _
        View:=acViewReport, _
        WhereCondition:=strWhere, _
        OpenArgs:=strHeader
    

    And in the report's load event you can check whether you got something in OpenArgs and use it:

    If Len(Me.OpenArgs) > 0 Then
        ' do what you want with it '
    End If
    

    This approach makes the report independent from any particular form. The strategy does not break if you rename the current form or create a different form for report selection criteria.

    You could even designate an appropriate header when report criteria are standardized in advance. For example, a command button captioned "View Yesterday's Additions":

    strWhere = "[Date_Added] >= (Date() - 1) AND [Date_Added] < Date()"
    strHeader = "Species Added Yesterday"
    DoCmd.OpenReport ReportName:="YourReport", _
        View:=acViewReport, _
        WhereCondition:=strWhere, _
        OpenArgs:=strHeader