Microsoft Access Database Development With VBA

Conditionally Opening a Form or Report

   

Introduction

Imagine you create a form that shows the records of a table or query. When navigating among the records, imagine the user comes to a particular record he or she wants to print. If you simply write normal code to open the related report, it would show all records from the beginning. Fortunately, Microsoft Access provides an easy mechanism to execute such a scenario.

If you add a button to a form in Design View, if the Button Wizard starts, you can follow it to select the report that would be opened when a button is clicked. Microsoft Access would write the code for you:

Private Sub cmdPreviewRentalOrder_Click()
On Error GoTo Err_cmdPreviewRentalOrder_Click

    Dim stDocName As String
    Dim strWHERECondition As String

    stDocName = "RentalOrders"
    strWHERECondition = "RentalOrderID = " & RentalOrderID
    DoCmd.OpenReport stDocName, acPreview, , strWHERECondition

Exit_cmdPreviewRentalOrder_Click:
    Exit Sub

Err_cmdPreviewRentalOrder_Click:
    MsgBox Err.Description
    Resume Exit_cmdPreviewRentalOrder_Click
    
End Sub
     
 

Home Copyright © 2011-2013 FunctionX, Inc. Home