【发布时间】:2021-05-21 08:42:32
【问题描述】:
我在 Access (Q_Invoices) 中有一个查询,该查询具有基于发票编号 (Invoice_Number) 的单独记录。我还有一份链接到此查询的报告 (R_Invoices_PDF)。我想做的是让 VBA 代码遍历查询中的每条记录,并将记录打印为报告中的单独 PDF。
我从某个网站复制了以下代码,并尝试根据我的目的对其进行调整。它在一定程度上起作用。但是,我在它循环之前停止它,它会保存所有记录,而不仅仅是第一个。
Private Sub cmd_GenPDFs_Click()
Dim rs As DAO.Recordset
Dim sFolder As String
Dim sFile As String
On Error GoTo Error_Handler
sFolder = "D:\Documents\Orchestra\Invoices\Invoice files\"
Set rs = CurrentDb.OpenRecordset("SELECT Invoice_Number FROM Q_Invoices", dbOpenSnapshot)
With rs
.MoveFirst
Do While Not .EOF
DoCmd.OpenReport "R_Invoices_PDF", acViewPreview, , "[Invoice_Number]=" & ![Invoice_Number], acHidden
sFile = Nz(![Invoice_Number], "") & ".pdf"
sFile = sFolder & sFile
DoCmd.OutputTo acOutputReport, "R_Invoices_PDF", acFormatPDF, sFile, acExportQualityPrint
'If you wanted to create an e-mail and include an individual report, you would do so now
DoCmd.Close acReport, "R_Invoices_PDF"
.MoveNext
Loop
End With
Application.FollowHyperlink sFolder 'Optional / Open the folder housing the files
Error_Handler_Exit:
On Error Resume Next
If Not rs Is Nothing Then
rs.Close
Set rs = Nothing
End If
Exit Sub
Error_Handler:
If Err.Number <> 2501 Then 'Let's ignore user cancellation of this action!
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: cmd_GenPDFs_Click" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Sub
【问题讨论】:
-
我在它循环之前停止它,它会保存所有记录,而不仅仅是第一个。 如果“saves”的意思是“打印为 PDF”,那可能是你打算这样做......但显然通过魔法,因为你“在它循环之前停止它”。这没有任何意义。
-
我的意思是,我按F8逐行运行它,以测试代码。在它循环之前,我检查了发生了什么,它已将所有发票记录保存到一个 PDF 文件中。我想要每条记录都有一个单独的 PDF。显然没有必要让代码继续运行,因为它没有按预期工作。这对你现在有意义吗?
-
顺便问一下,“打印到 PDF”和“保存到 PDF”不是同义词吗?