How to create a new report for an MS Access table programmatically using VBA

This procedure (sub) will create a report for the given table dynamically by adding all the fields found in the table. If “_P” is passed to the 2nd parameter, it will create report in portrait report, if “_L” is passed, it will create a landscape report.

Public Sub CreateNewReportForThisTable(tblName As String, P_L As String)
 Dim rpt As Report, rptNameJustCreated As String, rptNameFinal As String
 rptNameFinal = "rpt" & StrConv(tblName, vbProperCase) & P_L
 
 If reportExistsInTheDatabase(rptNameFinal) Then
    MsgBox rptNameFinal & " already exists in the database"
    'DoCmd.DeleteObject acForm, rptNameJustCreated
 Else
    Set rpt = CreateReport(, "rptBlankReport")
    rptNameJustCreated = rpt.Name
    'MsgBox rptNameJustCreated
    
    With rpt
        .RecordSource = tblName
        .Section(0).Height = 400 ' Form Detail
        .Section(1).Visible = True  ' Form Header
        .Section(1).Height = 400 ' Form Header
        '.Section(1).DisplayWhen = 0  ' Form Header
        '.Section(2).Height = 100 ' Form Footer
        If P_L = "_L" Then
            .Printer.Orientation = acPRORLandscape
            .Width = 10 * 1440 ' 10 Inch, Leave 1 Inch for Margins
        Else
            .Printer.Orientation = acPRORPortrait
            .Width = 7.5 * 1440 ' 7.5 Inch, Leave 1 Inch for Margins
        End If
        
    End With
    
    DoCmd.Save acReport, rptNameJustCreated
    DoCmd.Close acReport, rptNameJustCreated
    DoCmd.Restore
    DoCmd.Rename rptNameFinal, acReport, rptNameJustCreated
    
    'Add Controls to the Report that was just created
    Call AddControlsToTheReportOfThisTable(tblName, P_L)
 'This procedure does most of the work
    
 End If
 
End Sub

This is a complimentary article written by the MAARS team for the MAARS user community. Code in this article drives the operation of MAARS (MS Access Application wRiting Software). MAARS is an intelligent automation program that speeds up MS Access Application Development by 10x, 20x or 100x times. To learn more about MAARS, click here.

Disclaimer:

Some information included in this article may have been sourced from other publicly available websites and blogs. In such cases, credit goes to those authors for the original ideas and thoughts, but we do take credit for putting valuable information together and improve the efficiency of other office developers.