如何循环遍历 Excel 中的报表参数列表并使用 VBA 自动生成 .PDF 格式的报表服务器报表?

How do I loop through a list of report paramaters in Excel and automatically generate Report Server Reports as .PDF using VBA?

我有一个名为 "Customer Statement" 的 SSRS 报告,以及一大列客户 ID 和客户购买的相关产品。例如:

...(约 10,000 条记录)

报告生成客户报表并有两个参数,一个用于报告类型,一个用于客户 ID。

我需要为每个客户保存一个单独的 .PDF 导出报告,并将其放入一个名为客户 ID 的文件夹中。 EG "C1222.pdf"

我已经解决了一半的问题,我可以使用看起来像这样的 URL 从报表服务器直接下载 .PDF 文件:

http://myreportserver/ReportServer/Pages/ReportViewer.aspx?%2fCustomer+Reports%2fCustomer+Statement&rs:Format=PDF&rs:ClearSession=true&Product=Broadband&CustomerID=C1222

在网络浏览器中打开 link 会自动将报告下载为名为 "Customer Statement.pdf" 的 .PDF 文件,并传递正确的参数。

我需要的是遍历整个列表并为每一行生成一个文件,并将相关参数传递到 URL。 .PDF 的文件名必须是列表中的客户 ID。

理想情况下,我想在 Excel 中使用 VBA 宏执行此操作,但我愿意使用 Powershell、SQL 服务器甚至 Windows 批处理文件,如果那样会更容易。

编辑:

我有 SSRS 标准版,所以 "Data-Driven Subscription" 不适合我。

经过大量谷歌搜索和反复试验后,我有了一个可行的解决方案。

我将我的列表放入 Excel 中名为 "Control" 的工作表的 A 列和 B 列,并在 C 列中添加了一个文件夹名称,以便每个产品类型的报表转到不同的文件夹。然后我 运行 这个 VBA 在工作表上:

Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub DownloadStatements()

Dim wb As Workbook
Set wb = ThisWorkbook
Dim Product As String
Dim CustomerID As String

'Loop down all records in Control sheet
For x = 2 To wb.Sheets("Control").Range("A1").CurrentRegion.Rows.Count

    'Set CustomerID to the relevant value
    CustomerID = wb.Sheets("Control").Range("A" & x).Value

    'Set ClientString to the relevant value
    Product = wb.Sheets("Control").Range("B" & x).Value

    'Set download filename to CustomerID + ".pdf"
    DownloadFile$ = CustomerID & ".pdf"

    'Set download URL as the report URL, passing in the Product and CustomerID as paramaters
    Url$ = "http://myreportserver/ReportServer/Pages/ReportViewer.aspx?%2fCustomer+Reports%2fCustomer+Statement&rs:Format=PDF&rs:ClearSession=true&CustomerID=" & CustomerID & "&Product=" & Product

    'Set local download location based on main output folder cell and output subfolder cell for the specific row
    LocalFilename$ = wb.Sheets("Control").Range("E2").Value & wb.Sheets("Control").Range("C" & x) & DownloadFile

    'Download the file (in a slightly cheaty way)
    On Error Resume Next
    Debug.Print "Some junk text " & URLDownloadToFile(0, Url, LocalFilename, 0, 0) = 0
    On Error GoTo 0

Next x

End Sub

一切都完美,Excel 将坐在那里并在创建 .PDF 文件的列表中翻腾,速度非常快,并且很容易进一步自动化!