Opening a custom Crystal Report from code

Have you ever wanted to call your own Crystal Report from a custom user form? Here is how…

In this example I have a UserForm, a button, a text field for the constituent id and a Crystal Report Control. You will need to go to the control toolbox and add this control before it can be added to your form. All of the constants (variables in upper case) have been previously defined somewhere in the code.

Private Sub cmdReport_Click() 

    Dim sMsg As String    
    CrystalReport1.Connect = "DSN = " + ODBCSource + ";UID = " + DBUID + ";PWD = " + DBPWD 

    CrystalReport1.ReportFileName = REPORT_LOC 
    CrystalReport1.Formulas(0) = "CurrentConstituent=" & txtConstituentId.text 
    CrystalReport1.Destination = crptToWindow 
    CrystalReport1.PrintReport 

    sMsg = CrystalReport1.LastErrorString 

    If Not sMsg = "" Then 
        MsgBox sMsg 
    End If 

End Sub

Many of the parameters for the Crystal Report control can be entered into the parameters box in the IDE but for the greatest flexibility it is possible to steer everything in the code too.

The most useful is the formulas collection. In my Crystal Report I have parameter called “CurrentConstituent”. I use this parameter to filter the records to be shown. In this case it will only show the specific constituent’s details. You can decide where the Crystal should appear using the Destination parameter. Most commonly you will want this to go the the screen but you may want it to be printed directly.

If there is an error in displaying the report then the LastErrorString will let you know what it is and is a good way of debugging the link to Crystal.

One thought on “Opening a custom Crystal Report from code

Comments are closed.