使用VBA通过ID分隔打印到PDF

时间:2017-08-02 08:39:52

标签: vba ms-access pdf

我想为每个ID打印Access 2010报告。

让我们说我的报告结构是这样的:

ID1,    Name1,    phone1,   address1,

ID1,    Name2,    phone2,   address2,

ID2,    Name,    phone,   address,

ID3,    Name1,    phone1,   address1,

ID3,    Name2,    phone2,   address2,

我想要的是将每个ID写入单独的.pdf文件,如下所示:

ID1.pdf包含:

ID1,    Name1,    phone1,   address1,

ID1,    Name2,    phone2,   address2,

ID2.pdf包含:

ID2,    Name,    phone,   address,

ID3.pdf包含:

ID3,    Name1,    phone1,   address1,

ID3,    Name2,    phone2,   address2,

我创建了以下代码:

Private Sub PrintPDF_Click()

Dim rst As DAO.Recordset
Dim OutputFile As String
Dim FileSavePath As String

FileSavePath = "C:\Test\"
Set rst = CurrentDb.OpenRecordset("SELECT distinct ID FROM Report_Query ORDER BY _ID")
With rst
Do Until .EOF

DoCmd.OutputTo acOutputReport, Bericht1, acFormatPDF, FileSavePath & ![ID] & ".pdf", True

.MoveNext

Loop

End With

End Sub

Naming运行良好,但它会打印所有记录。我有ID1.pdf,ID2.pdf和ID3.pdf,但每个文件都包含所有记录。

如何为每个ID生成一个文件?

1 个答案:

答案 0 :(得分:0)

试试这种方式。

1)提取所有不同的ID

2)将记录集转换为数组

3)为每个ID循环数组

4)保存为PDF

未经过测试

    Private Sub PDF_Click()
    Dim rst As DAO.Recordset
    Dim OutputFile As String
    Dim FileSavePath As String
    Dim vArray As Variant
    Set rst = CurrentDb.OpenRecordset("SELECT distinct ID FROM Report_Query ORDER BY ID")
    With rst
        .MoveLast
        .MoveFirst
        vArray = .GetRows(.RecordCount)
    End With
    For Each ID In vArray
       FileSavePath = "C:\Test\" & Format(ID, "000000") & ".pdf"
    ' execute Query here
    '("select * from Report_Query where ID = " & ID )
    'save recordset in PDF format here
    Next ID
    End Sub