Connecting Tech Pros Worldwide Help | Site Map

Create Dynamic Report using VBA

msquared's Avatar
Administrator
 
Join Date: Aug 2006
Location: Dublin, Ireland
Posts: 10,865
#1   Aug 20 '07
This article contains three different approaches to creating dynamic reports.
  • Dynamic report from user defined SQL SELECT statement (Author: mmccarthy)
  • Dynamic report designed to be used with Crosstab Queries (Author: Nico5038)
  • Dynamic report creation via AutoReport command (Author: FishVal)
Dynamic report from user defined SQL SELECT statement
You will sometimes find yourself in a position where you need to allow the users to create dynamic reports based on a user defined query. The following function will create such a report when passed any appropriate SQL SELECT statement.

Expand|Select|Wrap|Line Numbers
  1. Function CreateDynamicReport(strSQL As String)
  2. Dim db As DAO.database ' database object
  3. Dim rs As DAO.Recordset ' recordset object
  4. Dim fld As DAO.Field ' recordset field
  5. Dim txtNew As Access.TextBox ' textbox control
  6. Dim lblNew As Access.Label ' label control
  7. Dim rpt As Report ' hold report object
  8. Dim lngTop As Long ' holds top value of control position
  9. Dim lngLeft As Long ' holds left value of controls position
  10. Dim title As String 'holds title of report
  11.  
  12.      'set the title
  13.      title = "Title for the Report"
  14.  
  15.      ' initialise position variables
  16.      lngLeft = 0
  17.      lngTop = 0
  18.  
  19.      'Create the report
  20.      Set rpt = CreateReport
  21.  
  22.      ' set properties of the Report
  23.      With rpt
  24.          .Width = 8500
  25.          .RecordSource = strSQL
  26.          .Caption = title
  27.      End With
  28.  
  29.      ' Open SQL query as a recordset
  30.      Set db = CurrentDb
  31.      Set rs = db.OpenRecordset(strSQL)    
  32.  
  33.      ' Create Label Title
  34.      Set lblNew = CreateReportControl(rpt.Name, acLabel, _
  35.      acPageHeader, , "Title", 0, 0)
  36.      lblNew.FontBold = True
  37.      lblNew.FontSize = 12
  38.      lblNew.SizeToFit
  39.  
  40.      ' Create corresponding label and text box controls for each field.
  41.      For Each fld In rs.Fields
  42.  
  43.          ' Create new text box control and size to fit data.
  44.          Set txtNew = CreateReportControl(rpt.Name, acTextBox, _
  45.          acDetail, , fld.Name, lngLeft + 1500, lngTop)
  46.          txtNew.SizeToFit
  47.  
  48.          ' Create new label control and size to fit data.
  49.          Set lblNew = CreateReportControl(rpt.Name, acLabel, acDetail, _
  50.          txtNew.Name, fld.Name, lngLeft, lngTop, 1400, txtNew.Height)
  51.          lblNew.SizeToFit        
  52.  
  53.          ' Increment top value for next control
  54.          lngTop = lngTop + txtNew.Height + 25
  55.      Next
  56.  
  57.      ' Create datestamp in Footer
  58.      Set lblNew = CreateReportControl(rpt.Name, acLabel, _
  59.      acPageFooter, , Now(), 0, 0)
  60.  
  61.      ' Create page numbering on footer
  62.      Set txtNew = CreateReportControl(rpt.Name, acTextBox, _
  63.      acPageFooter, , "='Page ' & [Page] & ' of ' & [Pages]", rpt.Width - 1000, 0)
  64.      txtNew.SizeToFit
  65.  
  66.      ' Open new report.
  67.      DoCmd.OpenReport rpt.Name, acViewPreview
  68.  
  69.      'reset all objects
  70.      rs.Close
  71.      Set rs = Nothing
  72.      Set rpt = Nothing
  73.      Set db = Nothing
  74.  
  75. End Function
  76.  

This report will not be saved until the user saves it or tries to close it. At which point they will be prompted to save it. You can play around with the layout of the report using the lngTop and lngLeft variables.

To call this function you simply need to pass a String parameter of a SQL statement to it as per the following.

CreateDynamicReport "SELECT * FROM TableName"

To create that SQL SELECT statement you can set up a form to allow the user to select options to build the query. There is no facility in this code to validate the SQL query as it is assumed this is done elsewhere. But thats another article.


Dynamic report designed to be used with Crosstab Queries

This code is especially "tuned" for crosstab queries. As I like to have control over the layout, thus I have the lay-out designed first with "coded" controls. Then the dynamic filling becomes very easy. The raw text I use to help with this is:

Making the columnheader and detaildata flexible is possible, but needs some VBA code in the OpenReport event.

To start, doing this you need to place the fields "coded" in the report.
The column headings should be called "lblCol1", "lblCol2", "lblCol3", etc.
The "detail" fields should be called "Col1", "Col2", "Col3", etc.

The report query has two rowheader columns and a Total column, therefore the first field is effectively column 4 (count starts at 0 so I used intI=3) but this could differ for you.

Make sure that the number of Columns is not bigger than the number placed. The program code has no protection against that.

The code needed for the open report event is:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Report_Open(Cancel As Integer)
  2. Dim intI As Integer
  3. Dim rs As Recordset
  4.  
  5.      Set rs = CurrentDb.OpenRecordset(Me.RecordSource)
  6.  
  7.      'Place headers
  8.      For intI = 3 To rs.Fields.Count - 1
  9.          Me("lblCol" & intI - 1).Caption = rs.Fields(intI).Name
  10.      Next intI
  11.  
  12.      'Place correct controlsource
  13.      For intI = 3 To rs.Fields.Count - 1
  14.          Me("Col" & intI - 1).ControlSource = rs.Fields(intI).Name
  15.      Next intI
  16.  
  17.      'Place Total field
  18.      Me.ColTotal.ControlSource = "=SUM([" & rs.Fields(2).Name & "])"   
  19.  
  20. End Sub
  21.  
The report query has two rowheader columns and a Total column, therefor the first field is effectively column 4 (count starts at 0 so I used intI=3) but it could differ for you.


Dynamic report creation via AutoReport command
This code is used for dynamic report creation using the AutoReport command. You will first need to create a query and call it "qryDummy". This query is used by the code but the resulting report will not be based on the query as this would invalidate the report when the query was next changed.

Expand|Select|Wrap|Line Numbers
  1. Public Sub CreateAutoReport(strSQL As String)
  2. Dim rptReport As Access.Report
  3. Dim strCaption As String
  4.  
  5.      CurrentDb.QueryDefs("qryDummy").SQL = strSQL
  6.  
  7.      ' Open dummy query to invoke NewObjectAutoReport command on it
  8.      ' Put the report created to design view to make properties editable
  9.      With DoCmd
  10.          .OpenQuery "qryDummy", acViewNormal
  11.          .RunCommand acCmdNewObjectAutoReport
  12.          .Close acQuery, "qryDummy"
  13.          .RunCommand acCmdDesignView
  14.      End With
  15.  
  16.      ' Get reference to just created report
  17.      For Each rpt In Reports
  18.          If rpt.Caption = "qryDummy" Then Set rptReport = rpt
  19.      Next
  20.  
  21.      With rptReport
  22.  
  23.          ' Create title control
  24.          With CreateReportControl(.Name, acLabel, _
  25.              acPageHeader, , "Title", 0, 0)
  26.              .FontBold = True
  27.              .FontSize = 12
  28.              .SizeToFit
  29.          End With
  30.  
  31.          ' Create timestamp on footer
  32.          CreateReportControl .Name, acLabel, _
  33.              acPageFooter, , Now(), 0, 0
  34.  
  35.          ' Create page numbering on footer
  36.          With CreateReportControl(.Name, acTextBox, _
  37.              acPageFooter, , "='Page ' & [Page] & ' of ' & [Pages]", _
  38.              .Width - 1000, 0)
  39.              .SizeToFit
  40.          End With
  41.  
  42.          ' Detach the report from dummy query
  43.          .RecordSource = strSQL
  44.  
  45.          ' Set the report caption to autogenerated unique string
  46.          strCaption = GetUniqueReportName
  47.          If strCaption <> "" Then .Caption = strCaption
  48.  
  49.      End With
  50.  
  51.      DoCmd.RunCommand acCmdPrintPreview
  52.  
  53.      Set rptReport = Nothing
  54.  
  55. End Sub
  56.  
  57.  
  58. Public Function GetUniqueReportName() As String
  59. Dim intCounter As Integer
  60. Dim blnIsUnique As Boolean
  61.  
  62.      For intCounter = 1 To 256 
  63.          GetUniqueReportName = "rptAutoReport_" & Format(intCounter, "0000")
  64.          blnIsUnique = True
  65.          For Each rpt In CurrentProject.AllReports
  66.              If rpt.Name = GetUniqueReportName Then blnIsUnique = False
  67.          Next
  68.          If blnIsUnique Then Exit Function
  69.      Next
  70.  
  71.      GetUniqueReportName = ""
  72.  
  73. End Function
  74.  



Newbie
 
Join Date: Nov 2007
Posts: 2
#2   Nov 8 '07

re: Create Dynamic Report using VBA


Hello,
I am sorry I don't know exactly the coding of how VBA generate autoreport in ACCESS, could you please indicate the command/ coding?
Many thanks,
Rock
Newbie
 
Join Date: Nov 2007
Posts: 2
#3   Nov 8 '07

re: Create Dynamic Report using VBA


Hello,
If I have some tables, and want to use a form (with a button) to call the autoreport function by selecting one of the tables, then how can I do it??
Please give me some suggestions.
Many thanks!!
Rock
Newbie
 
Join Date: Jan 2008
Posts: 2
#4   Jan 21 '08

re: Create Dynamic Report using VBA


I was wondering how one would dynamically change the sizing of the columns in the field. Creating an auto report is nice but its messy. Here is the code I have now


Expand|Select|Wrap|Line Numbers
  1. Public Function StaticReportGen(SQLStr As String, Title As String, layout As String) As Boolean
  2.     Dim strReportName       As String
  3.     Dim rpt                 As Report
  4.     Dim FieldName           As Field
  5.     Dim RS                  As Recordset
  6.     Dim intI                As Integer
  7.     Dim ctrl                As Control
  8.     Dim ColWidth            As Integer
  9.     Dim FirstCol            As Boolean
  10.     Dim TextWidth           As Integer
  11.     Dim TextCol             As Boolean
  12.     Dim TextBoxes           As Collection
  13.     Dim Labels              As Collection
  14.     Dim rsLengthCheck       As ADODB.Recordset
  15.     Dim objConn             As ADODB.Connection
  16.  
  17.     On Error GoTo rptErrHandler
  18.  
  19.     ColWidth = 0
  20.     TextWidth = 0
  21.     TextCol = True
  22.     FirstCol = True
  23.  
  24.     Set rpt = CreateReport()
  25.     strReportName = rpt.Name
  26.     rpt.Caption = Title
  27.  
  28.     DoCmd.RunCommand acCmdDesignView
  29.     DoCmd.Save acReport, strReportName
  30.     DoCmd.Close acReport, strReportName, acSaveNo
  31.     DoCmd.Rename Title, acReport, strReportName
  32.     DoCmd.OpenReport Title, acViewDesign
  33.     Set rpt = Reports(Title)
  34.  
  35.     'set printer stuff
  36.     rpt.Printer.BottomMargin = 360
  37.     rpt.Printer.LeftMargin = 360
  38.     rpt.Printer.RightMargin = 360
  39.     rpt.Printer.TopMargin = 360
  40.  
  41.     If layout = "Landscape" Then
  42.         rpt.Printer.Orientation = acPRORLandscape
  43.     Else
  44.         rpt.Printer.Orientation = acPRORPortrait
  45.     End If
  46.  
  47.     Set RS = CurrentDb.OpenRecordset(SQLStr)
  48.     rpt.RecordSource = SQLStr
  49.  
  50.     'create label on pageheader
  51.     For Each FieldName In RS.Fields
  52.         CreateReportControl Title, acLabel, acPageHeader, , FieldName.Name, 0, 0
  53.         CreateReportControl Title, acTextBox, acDetail, , FieldName.Name, 0, 0
  54.         '
  55.     Next FieldName
  56.  
  57.     'arrange fields
  58.     For Each ctrl In rpt.Controls
  59.  
  60.         Select Case ctrl.ControlType
  61.             Case acTextBox
  62.                 If TextCol Then
  63.                     ctrl.Name = ctrl.ControlSource
  64.                     ctrl.Move TextWidth, 0, ctrl.WIDTH, ctrl.Height
  65.                     TextWidth = TextWidth + ctrl.WIDTH
  66.                 Else
  67.                     ctrl.Name = ctrl.ControlSource
  68.                     ctrl.Move TextWidth, 0, ctrl.WIDTH, ctrl.Height
  69.                     TextWidth = TextWidth + ctrl.WIDTH
  70.                 End If
  71.                 TextCol = False
  72.             Case acLabel
  73.                 If FirstCol Then
  74.                     ctrl.Name = "lbl" & ctrl.Caption
  75.                     ctrl.Move ColWidth, 0, ctrl.WIDTH, ctrl.Height
  76.                 Else
  77.                     ctrl.Name = "lbl" & ctrl.Caption
  78.                     ctrl.Move TextWidth, 0, ctrl.WIDTH, ctrl.Height
  79.                 End If
  80.                 ctrl.FontSize = 10
  81.                 ctrl.FontWeight = 700
  82.                 FirstCol = False
  83.             Case Else
  84.  
  85.         End Select
  86.  
  87.     Next ctrl
  88.     'create line
  89.     CreateReportControl Title, acLine, acPageHeader, , , 0, 300, rpt.WIDTH
  90.  
  91.     'create title
  92.     CreateReportControl Title, acLabel, acHeader, , Title, 0, 0
  93.     CreateReportControl Title, acTextBox, acHeader, , Chr(61) & Chr(34) & "Printed on:   " & Chr(34) & "& Date() ", 0, 300
  94.  
  95.     For Each ctrl In rpt.Controls
  96.  
  97.         Select Case ctrl.ControlType
  98.             Case acTextBox
  99.                 If ctrl.Section = 1 Then
  100.                     ctrl.FontWeight = 700
  101.                     ctrl.FontSize = 14
  102.                     ctrl.Height = 350
  103.                     ctrl.WIDTH = 3500
  104.                     ctrl.Top = 400
  105.                 End If
  106.  
  107.             Case acLabel
  108.                 If ctrl.Section = 1 Then
  109.                     ctrl.FontSize = 16
  110.                     ctrl.FontWeight = 700
  111.                     ctrl.Height = 350
  112.                     ctrl.WIDTH = 3500
  113.                 End If
  114.         End Select
  115.  
  116.     Next ctrl
  117.  
  118.     'size fields correctly
  119.     For Each ctrl In rpt.Controls
  120.  
  121.         Select Case ctrl.ControlType
  122.  
  123.             Case acTextBox
  124.                 For Each FieldName In RS.Fields
  125.                     If ctrl.Name = FieldName Then
  126.  
  127.                     End If
  128.                 Next FieldName
  129.  
  130.             Case acLabel
  131.  
  132.         End Select
  133.  
  134.     Next ctrl
  135.  
  136.     DoCmd.Save acReport, Title
  137.     DoCmd.OpenReport Title, acViewPreview
  138.     StaticReportGen = True
  139.     Exit Function
  140.  
  141. rptErrHandler:
  142.     Select Case Err.Number
  143.     End Select
  144.     StaticReportGen = False
  145.     Debug.Print Err.Number
  146.     Debug.Print Err.Description
  147.     Exit Function
  148. End Function
  149.  

I want to use the textwidth property just having a block.
Newbie
 
Join Date: Aug 2008
Location: TN
Posts: 23
#5   Aug 26 '08

re: Create Dynamic Report using VBA


Can you set a dynamic report to be tabular automatically?

Also, could somebody show what the code would look like to add groupings to a dynamic report?

I try

with rpt

.GroupLevel(0).controlsource = me.combo1.value

but keep getting "Error, no grouping or sorting command given"

Thanks.
Reply