在您正在使用的表单上创建一个按钮,并将以下内容添加到其 Click 事件中。确保将MyReportName更改为实际的报告名称。 MyReportName在下面的代码中出现了两次。
On Error Resume Next
DoCmd.Close acReport, "MyReportName"
DoCmd.DeleteObject acQuery, "AuditPTETotalsDateRange"
On Error GoTo Err_cmd_Click
Dim strSQL, strSQL1 As String
Dim qdef As DAO.QueryDef
strSQL = "SELECT CUSTOMER.regNum, CUSTOMER.companyName, ScrapTireType.description, ScrapTireType.PTEamount, ScrapCollectionTireType.amount, ScrapCollection.PTEtotal, ScrapCollection.Date " & _
"FROM (ScrapCollection INNER JOIN CUSTOMER ON ScrapCollection.regNum = CUSTOMER.regNum) INNER JOIN (ScrapTireType INNER JOIN ScrapCollectionTireType ON (ScrapTireType.scrapTireTypeID = ScrapCollectionTireType.scrapTireTypeID) AND (ScrapTireType.scrapTireTypeID = ScrapCollectionTireType.scrapTireTypeID)) ON ScrapCollection.scrapCollectionID = ScrapCollectionTireType.scrapCollectionID " & _
"WHERE (((ScrapCollection.Date) Between #" & [Forms]![AuditPTETotals]![startDate] & "# And #" & [Forms]![AuditPTETotals]![endDate] & "#))"
strSQL1 = "TRANSFORM Sum(AuditPTETotalsDateRange.PTEtotal) AS SumOfPTEtotal " & _
"SELECT AuditPTETotalsDateRange.companyName, AuditPTETotalsDateRange.regNum, Sum(AuditPTETotalsDateRange.PTEtotal) AS [Total Of PTEtotal] " & _
"FROM AuditPTETotalsDateRange " & _
"GROUP BY AuditPTETotalsDateRange.companyName, AuditPTETotalsDateRange.regNum " & _
"PIVOT AuditPTETotalsDateRange.description"
Set qdef = CurrentDb.CreateQueryDef("AuditPTETotalsDateRange", strSQL)
Set qdef = CurrentDb.CreateQueryDef("AuditPTETotals_CrosstabDateRange", strSQL1)
DoCmd.OpenReport "MyReportName", acViewPreview
Exit_cmd_Click:
Exit Sub
Err_cmd_Click:
MsgBox Err.Description
Resume Exit_cmd_Click
然后在关闭事件的表单上添加以下内容:
On Error Resume Next
DoCmd.DeleteObject acQuery, "AuditPTETotalsDateRange"
然后发生的情况是,如果单击该按钮,AuditPTETTotalsDateRange 将被删除然后重新创建。此外,如果您关闭表单,则会删除 AuditPTETotalsDateRange 查询。这没关系,因为只有在表单打开时才需要查询。将报告的记录源设置为 AuditPTETotals_CrosstabDateRange。
您必须参考Microsoft DAO xx 对象库集才能使上述代码正常工作。您可能已经拥有参考集。xx 代表版本。任何版本都应该工作。
编辑
您可能希望在进行所有这些更改之前复制原始报告,以防它不适合您。尝试从报表上的字段中删除数据源,使其不受约束。然后将以下代码添加到打开事件的报告中:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("AuditPTETotals_CrosstabDateRange", dbOpenDynaset)
On Error Resume Next
[txtdata1].ControlSource = rs.Fields(4).Name
[txtData2].ControlSource = rs.Fields(5).Name
[txtData3].ControlSource = rs.Fields(6).Name
//And etc for as many fields as you have on report
您还可以以类似的方式在页眉上分配列标题。他们需要从标签更改为未绑定的文本框才能正常工作。将以下代码添加到页眉 On Format 事件中:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("AuditPTETotals_CrosstabDateRange", dbOpenDynaset)
On Error Resume Next
[txtColHeading1].value = rs.Fields(4).Name
[txtColHeading2].value = rs.Fields(5).Name
[txtColHeading3].value = rs.Fields(6).Name
//And etc for as many fields as you have on report
这将允许您在不知道您将拥有哪些列的情况下运行您的报告。确保您命名控件以匹配代码中此处的名称,反之亦然。