3

不久前,我从网上获得了以下 VBA 代码:

Private Sub btnCreatePDF_Click()
    Dim MyPath As String
    Dim MyFilename As String
    MyPath = "D:\reports\"
        MyFilename = "KS1.pdf"
    'Open report preview and auto-save it as a PDF
        DoCmd.OpenReport "Rpt_KS1", acViewPreview
        DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False 'Change false to true here to auto-open the saved PDF
    'Close the previewed report
        DoCmd.Close acReport, "Rpt_KS1"
End Sub

它用于在 MS Access 中创建单个 pdf 报告(最多包含 30 页),并且可以很好地满足我的需要。但是,我现在需要将报告分成 30 页左右,并为每一页创建一个 pdf。知道如何做到这一点吗?我在报告中有一个“用户名”,或者如果这有助于拆分它们等,可以添加一个唯一 ID。

4

1 回答 1

2

使用Docmd.OpenReport的第四个参数 (WhereCondition) 。使用 WhereCondition,完全按照您在向查询中添加 Where 时通常会执行的操作,只是不要包含单词 Where。这将使报表仅显示与 WhereCondition 匹配的记录。

将您的唯一标识符列表检索到某种集合或记录集中,然后执行循环。此示例假定您将它们放在一个名为 uniqueIds 的集合中,并且几乎肯定需要您进行一些修改。

Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\reports\"    
'Loop structure may vary depending on how you obtain values
For each uniqueId in uniqueIds
    MyFilename = "KS1" & uniqueId & ".pdf"
'Open report preview and auto-save it as a PDF
    DoCmd.OpenReport "Rpt_KS1", acViewPreview, , "uniqueField = " & uniqueID
    DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False
'Close the previewed report
    DoCmd.Close acReport, "Rpt_KS1"
Next uniqueId

严格来说,这可能不会导致每一页都有不同的 PDF。但它会为每个 uniqueID 生成不同的 PDF,这可能是每个页面,具体取决于您的数据。

于 2012-12-20T02:45:10.277 回答