设置报告的数据源

时间:2016-07-12 18:14:16

标签: access-vba ms-access-2010

我正在尝试在Access窗体中创建一个按钮,该窗体将运行几个查询,然后将结果记录集放入报告中。我已经达到了按钮将调用模块的程度,它创建了正确的记录集,然后创建了报告。但是,报告是空白的,它们没有记录集中的数据。我认为我的问题是我没有正确分配报告的数据来源,但我无法弄清楚如何解决这个问题。

Private Function showReport(sectionHeading As String, SQL As String, recordset As ADODB.Recordset)
Dim textBox As Access.textBox ' textbox control
Dim label As Access.label ' label control
Dim report As report ' hold report object
Dim controlTop As Long ' holds top value of control position
Dim controlLeft As Long ' holds left value of control position
Dim title As String 'holds title of report
Dim i As Integer 'iterator
i = 0

title = sectionHeading

controlLeft = 0
controlTop = 0

Set report = CreateReport

report.Width = 8500
report.Caption = title

Set label = CreateReportControl(report.Name, acLabel, _
acPageHeader, , "Title", 0, 0)
label.FontBold = True
label.FontSize = 12
label.SizeToFit

For Each fld In recordset.fields
    Set textBox = CreateReportControl(report.Name, acTextBox, _
    acDetail, , fld.Name, controlLeft + 1500, controlTop)
    textBox.SizeToFit

    Set label = CreateReportControl(report.Name, acLabel, acDetail, _
    textBox.Name, fld.Name, controlLeft, controlTop, 1400, textBox.Height)
    label.SizeToFit

    controlTop = controlTop + textBox.Height + 25

    i = i + 1
Next

Set label = CreateReportControl(report.Name, acLabel, _
acPageFooter, , Now(), 0, 0)

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

report.RecordSource = SQL

DoCmd.OpenReport report.Name, acViewPreview

recordset.Close
Set recordset = Nothing
Set report = Nothing
End Function

1 个答案:

答案 0 :(得分:2)

我说你错过了像

这样的一行
report.RecordSource = "the query that fills <recordset>"

但我非常确定必须有更好的方法来实现您的目标,而不是从头开始创建新报告。

并且容易将变量命名为数据类型(labelreport,...)

修改

您确定您的SQL有效吗?或者,您可以尝试将其另存为查询并传递查询名称。

我做了一点测试,它应该主要工作。我运行时r_tbProduct有一个空的记录源:

Dim rep As Report

DoCmd.OpenReport "r_tbProduct", acViewDesign
Set rep = Reports!r_tbProduct
rep.RecordSource = "SELECT * FROM tbProduct WHERE ID >= 6"
DoCmd.OpenReport "r_tbProduct", acViewPreview

显示正确的数据。

同样,我强烈建议您重命名变量。

Dim report As report

只是在问问题。