访问:将单个页面打印为pdf,单独命名的文件

时间:2015-07-21 04:42:44

标签: vba ms-access pdf access-vba

我尝试创建程序/宏/ VBA,以便在单个文件中打印发票到PDF。我希望文件名也用发票号命名。但我是Access编码的新手,虽然我可以在VBA中编写代码,所以我不知道我需要做什么命令来执行上述操作。这是我的计划:

  1. 为发票创建报告,以便在1页上创建1张发票。
  2. 循环遍历表/查询(带有EOF的循环,带有表大小的循环)
  3. 只要有下一条记录,就为它创建一个报告页面。
  4. 仅打印当前页面并使用相应的发票编号命名。
  5. 继续前进
  6. 我知道访问有一个工具可以创建宏来打印到PDF,但它会打印所有内容并且不会在单个页面上工作。这就是为什么我认为我应该使用循环。所以我想知道:

    - 有更好的方法吗?

    - 如果我必须这样做,那么我需要使用哪些命令。

    - 我见过人们使用这些代码:

        Dim db As DAO.Database
        Dim rs As DAO.Recordset
        Set rs = db.OpenRecordset("SELECT distinct [GROUP] FROM [REPORT]", dbOpenSnapshot)
    

    你能解释一下这些意思吗?

    另外,我在工作中这样做,所以我无法安装程序。我使用Access 2010

1 个答案:

答案 0 :(得分:2)

对于这样的问题,我会使用您报告的过滤功能...... - 构建一个查询,准备发票所需的所有数据(在我的情况下,发票) - 根据您查询INVOICE,构建一份打印所有发票的报告 - 使用" Where条件"打开报告时仅过滤1张发票 例如,以下代码为每张发票生成.pdf,pdf的名称为发票的ID。我使用INVOICE_ID作为发票的唯一ID

Option Compare Database
Option Explicit

Private Sub startInvoice_Click()

    Dim myrs As Recordset
    Dim myPDF, myStmt As String

    ' Open a record set with a list of invoice number to print
    myStmt = "SELECT distinct invoice_id from INVOICE"
    Set myrs = CurrentDb.OpenRecordset(myStmt)

    ' For each invoice, print in a .pdf
    Do Until myrs.EOF

        ' Set the output path of your PDF file invoice
        myPDF = "C:\temp\INVOICE_" & Format(myrs.Fields("INVOICE_ID"), "000000") & ".pdf"

        ' Open the report with the proper where condition
        DoCmd.OpenReport "INVOICE", acViewPreview, , "INVOICE_ID = " & myrs.Fields("invoice_id").Value

        ' Generate the output in pdf
        DoCmd.OutputTo objectType:=acOutputReport, objectName:="INVOICE", outputformat:=acFormatPDF, outputfile:=myPDF, outputquality:=acExportQualityPrint

        DoCmd.Close ' Close the report
        myrs.MoveNext ' read next

    Loop

    ' some cleanup
    myrs.Close
    Set myrs = Nothing

End Sub

希望这有帮助