循环记录集以将Ms-Access报告输出到pdf文件

时间:2017-11-15 10:11:26

标签: vba ms-access access-vba

我试图通过tenant_id使用docmd.outputTo获取pdf文件。不幸的是,这个例程产生的输出pdf文件都在同一个tenant_id中。如果我删除docmd.outputTo最后一个参数pathName & fileName,那么它需要通过对话文件名和输出文件tenant_id很好地过滤。任何帮助,将不胜感激。

以下是发票查询:SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()

Public Sub Output()
    Dim MyRs As DAO.Recordset
    Dim rpt As Report
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    DoCmd.OpenReport "Invoice", acPreview, , , acHidden
    Set rpt = Reports("Invoice")

    With MyRs
        .MoveFirst
            Do While Not .EOF
                fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
                rpt.Filter = "[tenant_id] = " & !tenant_id
                rpt.FilterOn = True
                DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
               .MoveNext
            Loop
    End With

End Sub

2 个答案:

答案 0 :(得分:1)

由于DoCmd.OutputTo缺少过滤参数,因此最好的选择是将报告基于公共函数以获取当前ID。

E.g。

' Function to both set and retrieve the current Tenant ID
Public Function CurTenantID(Optional SetTenantID As Long = 0) As Long

    Static TenantID As Long

    If SetTenantID > 0 Then
        TenantID = SetTenantID
    End If

    CurTenantID = TenantID

End Function

您的报告在其记录来源中使用此功能,例如

SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()

在循环中生成PDF报告时,使用SetTenantID参数:

Public Sub Output()

    Dim MyRs As DAO.Recordset
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    With MyRs
        ' .MoveFirst -- unneeded after OpenRecordset()
        Do While Not .EOF
            fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
            Call CurTenantID(!tenant_id)
            DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
            .MoveNext
        Loop
    End With

End Sub

答案 1 :(得分:1)

只需使用DoCmd.OpenReport方法过滤报告,然后根据文档将报告名称留空DoCmd.OutputTo

  

ObjectName>可选>变体:如果要输出活动对象,请为ObjectType参数指定对象的类型,并将此参数留空。

With MyRs
    .MoveFirst
    Do While Not .EOF
        fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"

        DoCmd.OpenReport "Invoice", acViewReport, , "[tenant_id] = " & !tenant_id, acHidden
        DoCmd.OutputTo acOutputReport, , acFormatPDF, pathName & fileName
        .MoveNext
    Loop
End With