循环访问Access中的所有报告

时间:2013-10-28 14:59:31

标签: ms-access-2010

我有一些代码可以在访问中构建基本报告,但是当我尝试使用我的变量rpt遍历所有报告时,它会跳过循环部分,因为没有为对象分配任何内容。有任何想法吗?我需要rpt来查找带有标题qryDummy的报告。提前致谢! : - )

 Dim rptReport As Access.Report
 Dim strCaption As String
 Dim rpt As Report     
 CurrentDb.QueryDefs("qryDummy").SQL = strSQL

     ' Open dummy query to invoke NewObjectAutoReport command on it
     ' Put the report created to design view to make properties editable

     With DoCmd
          .OpenQuery "qryDummy", acViewNormal
          .RunCommand acCmdNewObjectAutoReport
          .Close acQuery, "qryDummy"
          .RunCommand acCmdDesignView
      End With

      ' Get reference to just created report 

      ' !!!!!!!!!! This is the Section Giving me problems will !!!!!!!!!!!!!!  
      ' !!!!!!!!!! not loop through all the reports. !!!!!!!!!!!!!!!!!!!!!!!!!

      For Each rpt In Reports
          If rpt.Caption = "qryDummy" Then Set rptReport = rpt
      Next

      With rptReport

          ' Create title control

          With CreateReportControl(.Name, acLabel, _
              acPageHeader, , ReportTitle, 0, 0)
              .FontBold = True
              .FontSize = 12
              .SizeToFit
          End With

          ' Create timestamp on footer

          CreateReportControl .Name, acLabel, _
              acPageFooter, , Now(), 0, 0

          ' Create page numbering on footer

          With CreateReportControl(.Name, acTextBox, _
              acPageFooter, , "='Page ' & [Page] & ' of ' & [Pages]", _
              .Width - 1000, 0)
              .SizeToFit
          End With

          ' Detach the report from dummy query

          .RecordSource = strSQL

          ' Set the report caption to autogenerated unique string

          strCaption = GetUniqueReportName
          If strCaption <> "" Then .Caption = strCaption

      End With

      DoCmd.RunCommand acCmdPrintPreview

      Set rptReport = Nothing

编辑:

好的,所以我想我的问题会使用这段代码,因为报告在VBA运行时保持打开状态:

For Each rpt In Reports
          If rpt.Caption = "qryDummy" Then Set rptReport = rpt
      Next

我唯一的问题是它没有分配rptReport = rpt我得到错误:rpt = nothing,这导致rpt.caption =“对象变量或没有设置块变量”。那就像开放的报告没有被看到?

FYI解决了问题需要将rpt.caption更改为rpt.Name感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

Dim rpt As Report
For Each rpt In Reports
    Debug.Print rpt.Name
Next

只会遍历当前打开的Reports。要遍历所有报告,您需要执行

Dim rpt As Object
For Each rpt In Application.CurrentProject.AllReports
    Debug.Print rpt.Name
Next