Cat On A Spreadsheet

Building an Automated Reporting Pipeline with Power Query, Dynamic Arrays and VBA

Throughout this series, we have progressively expanded what Excel can do as a reporting tool. We started with individual dynamic-array techniques, moved into aggregation and time intelligence, developed reusable calculations with LAMBDA, and eventually built a configurable management reporting engine. In the most recent posts, we considered how to test that engine and how to turn it into a workbook that could be used and maintained reliably. We now have something rather useful: a workbook that can take a structured transaction dataset, interpret reporting controls and produce a management report automatically.

 

But one part of the process remains largely manual. Somebody still needs to obtain the source data, update the workbook, check that the report has recalculated, verify its results and prepare a copy for management review. Those steps may be manageable when the report is produced occasionally, but when they are repeated every week or month they become an obvious opportunity for automation.

 

The temptation is to write one large VBA procedure that performs everything. It could open the source file, copy its contents, clean the data, calculate the figures, construct the report, apply formatting and export a PDF. That approach would certainly be possible, and in some circumstances it might be appropriate - but Excel now provides several tools that are better suited to different parts of the process: Power Query is designed for acquiring and transforming data, dynamic arrays provide an expressive calculation engine and VBA can coordinate workbook actions, control presentation and prepare output files. Rather than making one technology responsible for everything, we can combine them into a reporting pipeline.

 

The objective is not to introduce as much automation as possible. It is to create a process that is easier to operate, less vulnerable to manual mistakes and sufficiently transparent that problems can be investigated when something goes wrong.

 

Understanding the reporting pipeline

 

Let's continue with the fictional transaction-reporting system used throughout the series. Our reporting engine expects an Excel Table called tblTransactions, containing Date, Department, Region, Category, Status and Value. Users can select a reporting period, choose the rows and columns of a management matrix, and select between total transaction value, transaction count and average transaction value.

 

We will assume that the source data comes from another business system, which produces an Excel export containing the transactions. The report will be prepared for management review, but it will not be distributed automatically. Approval and final distribution will remain separate decisions.

 

The overall process will have three main stages. First, Power Query will retrieve the exported transactions, establish their data types and load them into the expected Table. Next, dynamic-array formulas will calculate the reporting measures, construct the selected matrix and support validation and reconciliation checks, and then VBA will take a successfully calculated and reviewed report, create a static snapshot and prepare a draft PDF.

 

The important word here is static. An interactive Excel report can change whenever its source data or control cells change, however a  management report prepared for review should represent a fixed reporting position. We therefore need a clear transition from live calculation to frozen output.

 

That transition is one of the most useful responsibilities to give VBA.

 

Power Query as the data preparation layer

 

Consider how our workbook might work without Power Query: every month, the user exports a file, opens it, selects the transaction records, copies them and pastes them into the reporting workbook and, as long as the data is pasted correctly, the Excel Table expands and the formulas recalculate. There is nothing inherently wrong with that process - but it introduces several opportunities for mistakes. The user might copy the wrong range, omit the final records, paste an unexpected column arrangement or accidentally overwrite part of the reporting workbook.

 

Power Query allows us to replace those repeated manual steps with a defined connection and transformation process. We can use Excel's Data tab to import the source workbook, select the transaction table and open the Power Query Editor. There, we can select the required columns, assign their data types and make any necessary transformations. The result can be loaded directly into an Excel Table on a dedicated Data worksheet.

 

For a simple example, imagine that the source file is consistently stored at C:\Reporting\Input\Transactions.xlsx and contains a table named tblExport. The Power Query transformation can be expressed in M, the language used by Power Query:

let
     Source = Excel.Workbook(File.Contents("C:\Reporting\Input\Transactions.xlsx"), null, true),
     RawData = Source{[Item="tblExport", Kind="Table"]}[Data],
     SelectedColumns = Table.SelectColumns(RawData, {"Date", "Department", "Region", "Category", "Status", "Value"}),
     TypedData = Table.TransformColumnTypes(SelectedColumns, {{"Date", type datetime}, {"Department", type text}, {"Region", type text}, {"Category", type text}, {"Status", type text}, {"Value", type number}}, "en-IE")
in
     TypedData

 

The code is deliberately straightforward. Power Query opens the source workbook, retrieves the specified table, selects the fields needed by our reporting system and assigns their types. We use a date-and-time type for the transaction date because we do not want to discard time components unnecessarily. Our reporting formulas already use exclusive upper date boundaries, so a transaction recorded late on the final day of a month can be included correctly. The resulting query should be loaded to the Data worksheet as an Excel Table named tblTransactions.

 

The file path is illustrative and would need to be adapted to the actual environment. If the source is held in SharePoint, a supported SharePoint connection is preferable to assuming that everyone has the same locally synchronised folder path.

 

An important design decision is that we have not filtered the data to posted transactions in Power Query. Our reporting engine already has a clear business rule determining which statuses belong in the report. By retaining the source status field, we preserve the ability to examine excluded transactions and validate that rule. That does not mean business filtering should never happen in Power Query - it just means we should decide where a rule belongs and avoid having slightly different implementations scattered across several processing stages. For this workbook, Power Query is responsible for establishing a consistent source structure. The reporting calculation is responsible for determining which records belong to a particular management report.

 

We also need to be careful about how data problems are handled. If a transaction contains an invalid date or a non-numeric value, converting the column type may expose an error. That is useful information. Automatically replacing every conversion error with zero or silently removing the affected record might make the refresh appear cleaner, but it could also produce incorrect management figures. A reliable pipeline should identify unexpected source values and either reject the update or flag the affected records for investigation. The purpose of the transformation stage is to improve consistency, not to conceal defects in the source.

 

Dynamic arrays as the calculation layer

 

Once the Power Query result has been loaded into tblTransactions, the calculation layer can operate much as it did in the previous articles. This is a major advantage of maintaining a stable interface between the source data and the reporting formulas. The report does not need to know where the original export came from. It does not need to open the source workbook or understand its file format. It needs only the structured Table and the agreed meaning of its fields.

 

We can retain the reporting engine from our previous example, with the main dynamic-array formula anchored at Report!J10. That formula constructs a matrix based on the user selections in H2:H6. When the Power Query Table is updated, the structured references used by the engine expand or contract with the loaded data. Excel can then recalculate the report using the updated records. This is exactly the kind of work that dynamic arrays are well suited to performing.

 

There is little reason to move the matrix calculation into VBA simply because VBA will eventually be involved in generating the output. Doing so would mean maintaining another implementation of the reporting logic, potentially introducing differences between what users see in Excel and what the automation produces. Instead, we should preserve one authoritative calculation. The worksheet remains responsible for producing the report, and VBA will use that report as its input.

 

The same applies to our reconciliation checks. If the report is expected to contain posted transactions for January through March, the reconciliation formula should independently verify that the current result agrees with the corresponding source population. If the user switches from Total Value to Transactions, the validation should follow the new measure. For Average Value, the comparison must use the correct numerator and denominator rather than summing or averaging the displayed intersection averages. Those details belong to the calculation and validation layers. They should not need to be reimplemented in the PDF-export procedure.

 

This gives us a useful separation: the worksheet decides which figures are correct, while the automation decides whether those figures are ready to be converted into an output file.

 

Why refresh completion matters

 

We now reach a surprisingly important technical issue. It is tempting to begin a VBA procedure with ThisWorkbook.RefreshAll, calculate the report and immediately export a PDF. The code would look straightforward, but there is a potential timing problem. Excel can refresh some external-data connections in the background, but that means the VBA procedure might proceed while the new source records are still being retrieved. If the report is recalculated or exported too early, the resulting file could contain the previous dataset or an inconsistent intermediate state.

 

Simply adding DoEvents or waiting an arbitrary number of seconds is not a reliable solution. The necessary refresh duration will vary according to data volume, connection speed and source availability.

 

For some worksheet-loaded query connections, a synchronous refresh can be requested through the associated QueryTable.Refresh method with BackgroundQuery:=False. However, the exact refresh behaviour depends on how the query is connected and loaded. A workbook containing several queries, connection-only dependencies or Data Model loads may need more careful orchestration than one generic refresh command. For our first reporting pipeline, I would therefore keep refreshing and exporting as two distinct user actions. The user refreshes the Power Query data, confirms that the operation completed successfully and reviews the resulting report, and then VBAprepares the draft output.

 

That may sound less automated than a single button performing everything, but it creates a useful control point between data acquisition and report publication. Once the refresh method has been tested for the specific workbook, we can automate more of the sequence without sacrificing reliability. The important thing is not to claim that a refresh has finished merely because VBA has executed a refresh command.

 

Giving VBA responsibility for the output

 

Our report now exists as a live dynamic array. Suppose the output begins in cell J10 on the Report worksheet. The top row contains the headings, the first column contains the selected row dimension, and the remaining cells contain the reporting measures. The size of this output changes according to the selected reporting period and dimensions.

 

VBA needs to retrieve the entire current result, not a fixed address such as J10:Q30, and this is where the spill-range operator becomes useful again. In a worksheet formula, J10# refers to the complete result generated by the formula in J10 and, in a modern dynamic-array-enabled version of Excel, VBA can also use that spill reference to retrieve the current output range. For example, Worksheets("Report").Range("J10#") can represent the entire matrix regardless of how many rows and columns it currently contains. That allows us to design the export procedure without hard-coding the report dimensions.

 

We also need to consider what happens when the formula cannot produce a normal matrix. If the selected period is empty and the formula returns a message, there may be no valid multi-cell reporting table to export. If a spill obstruction occurs, the anchor may contain #SPILL!. The procedure should recognise these conditions and refuse to produce a management report rather than exporting an error message.

 

For our example, we will use a Checks worksheet containing two previously tested status cells. B2 will return "PASS" only when the current source data has passed its quality checks. B3 will return "PASS" only when the current report has passed the applicable reconciliation checks. The actual definitions of those checks must be implemented according to the workbook's business rules, using the testing techniques from the previous articles. They should not be hard-coded to return "PASS", and an Average Value report needs its own valid reconciliation.

 

These cells provide VBA with a simple interface. VBA does not need to understand the individual financial or operational calculations. It needs to know whether the established validation layer has accepted the current result. That is a practical example of separating responsibilities between the technologies.

 

Creating a static draft PDF

 

There is one more design decision before we write the macro. We could export the live Report worksheet directly to PDF. Excel supports that through the ExportAsFixedFormat method and, for a fixed-format report, this may be sufficient - but our report is interactive. The worksheet also contains control cells, reconciliation indicators and possibly other explanatory information that should not appear in the final management table.

 

I prefer to create a temporary workbook specifically for the output. VBA will retrieve the current report matrix, copy its values and formatting into a new worksheet, add an appropriate title and reporting-period description, and export that temporary worksheet as a PDF. The temporary workbook will then be closed without saving.

 

This gives us several advantages: the PDF contains the current results, not live formulas, it can be formatted independently of the interactive reporting interface, and its layout can be controlled specifically for printing and, most importantly, the process does not modify the underlying reporting calculation.

 

For this example, we will use a macro called ExportDraftManagementPDF. The procedure assumes that the Power Query refresh has already been completed and reviewed, the report is anchored at Report!J10, and the two validation results are available on Checks!B2:B3. It will ask the user to confirm that the source refresh has been checked, recalculate the workbook, verify the status cells, capture the current report and let the user choose where to save the PDF. It will not send the report to anyone or mark it as approved.

 

The complete VBA procedure is shown below. It belongs in a standard VBA module in the reporting workbook, which must be saved as an .xlsm file.

Option Explicit

Public Sub ExportDraftManagementPDF()

     Dim wsReport As Worksheet
     Dim wsChecks As Worksheet
     Dim wbDraft As Workbook
     Dim wsDraft As Worksheet
     Dim sourceRange As Range
     Dim targetRange As Range
     Dim outputPath As Variant
     Dim previousScreenUpdating As Boolean
     Dim errorMessage As String

     previousScreenUpdating = Application.ScreenUpdating
     On Error GoTo HandleError

     Set wsReport = ThisWorkbook.Worksheets("Report")
     Set wsChecks = ThisWorkbook.Worksheets("Checks")

     If MsgBox("Confirm that the source refresh completed successfully and the data is current.", vbYesNo + vbQuestion, "Verify Source") <> vbYes Then Exit Sub

     Application.CalculateFull

     If wsChecks.Range("B2").Value2 <> "PASS" Or wsChecks.Range("B3").Value2 <> "PASS" Then
         MsgBox "Validation checks have not passed. Review the workbook before exporting.", vbExclamation
         Exit Sub
     End If

     If IsError(wsReport.Range("J10").Value2) Then
         MsgBox "The reporting formula contains an error.", vbExclamation
         Exit Sub
     End If

     Set sourceRange = wsReport.Range("J10#")

     If sourceRange.Rows.Count < 2 Or sourceRange.Columns.Count < 2 Then
         MsgBox "The report does not contain a valid matrix.", vbExclamation
         Exit Sub
     End If

     outputPath = Application.GetSaveAsFilename( _
         InitialFileName:="Draft_Management_Report_" & Format(Now, "yyyymmdd_hhnn") & ".pdf", _
         FileFilter:="PDF Files (*.pdf),*.pdf", _
         Title:="Save Draft Management Report")

     If VarType(outputPath) = vbBoolean Then Exit Sub

     Application.ScreenUpdating = False

     Set wbDraft = Workbooks.Add(xlWBATWorksheet)
     Set wsDraft = wbDraft.Worksheets(1)
     wsDraft.Name = "Draft Report"

     Set targetRange = wsDraft.Range("A5").Resize(sourceRange.Rows.Count, sourceRange.Columns.Count)

     sourceRange.Copy
     targetRange.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
     targetRange.PasteSpecial Paste:=xlPasteFormats
     Application.CutCopyMode = False

     With wsDraft
         .Range("A1").Value = "DRAFT - FOR MANAGEMENT REVIEW"
         .Range("A2").Value = "Period: " & Format(wsReport.Range("H2").Value, "mmm yyyy") & " to " & Format(wsReport.Range("H3").Value, "mmm yyyy")
         .Range("A3").Value = wsReport.Range("H6").Value & " by " & wsReport.Range("H4").Value & " and " & wsReport.Range("H5").Value
         .Range("A1").Font.Bold = True
         .Range("A5").Resize(1, sourceRange.Columns.Count).Font.Bold = True
         .UsedRange.Columns.AutoFit

         With .PageSetup
             .Orientation = xlLandscape
             .Zoom = False
             .FitToPagesWide = 1
             .FitToPagesTall = False
         End With

         .PageSetup.PrintArea = .Range("A1").Resize(sourceRange.Rows.Count + 4, sourceRange.Columns.Count).Address

         .ExportAsFixedFormat Type:=xlTypePDF, _
             Filename:=CStr(outputPath), _
             Quality:=xlQualityStandard, _
             IgnorePrintAreas:=False, _
             OpenAfterPublish:=False
     End With

     wbDraft.Close SaveChanges:=False
     Set wbDraft = Nothing

     Application.ScreenUpdating = previousScreenUpdating
     MsgBox "Draft PDF created. Review it before distribution.", vbInformation
     Exit Sub

HandleError:
     errorMessage = Err.Description
     On Error Resume Next
     Application.CutCopyMode = False
     If Not wbDraft Is Nothing Then wbDraft.Close SaveChanges:=False
     Application.ScreenUpdating = previousScreenUpdating
     MsgBox "Draft export failed: " & errorMessage, vbExclamation
End Sub

 

The procedure is deliberately limited in scope. It does not attempt to retrieve source files, reconstruct the calculations or decide whether the financial results make sense. It assumes that the workbook already contains a functioning reporting calculation and meaningful validation checks an, if either of the validation cells fails, the export is stopped. If the spill range cannot be retrieved, the procedure reports an error rather than falling back to an arbitrary fixed range. If the user cancels the Save As dialog, no output file is created.

 

The report is copied using a values-and-formatting paste rather than a normal formula paste. That distinction matters because the temporary workbook should contain a frozen snapshot, not a second live copy of the reporting engine. The number formatting is also preserved, so a date header formatted as mmm yyyy does not unexpectedly become a raw Excel serial number. A newly created workbook provides a clean environment for the output, while the original reporting workbook remains unchanged.

 

Finally, the temporary workbook is closed without saving after the PDF has been generated.

 

This is the kind of task for which VBA is well suited. It coordinates a sequence of workbook operations and produces an output file, while leaving the data transformation and numerical calculations to other parts of the system.

 

Keeping the pipeline transparent

 

One danger with automation is that it can hide the stages through which data passes. A user presses a button, a PDF appears, and the intermediate activity becomes invisible. That may seem convenient, but it makes failures harder to investigate. For this reason, I would initially keep the source Table, dynamic report and reconciliation results accessible within the workbook. The user should be able to inspect the loaded transactions, review the report before exporting it and see why an output has been blocked. The macro should not silently correct data errors or override a failed reconciliation simply to complete the PDF generation.

 

There is also value in displaying the reporting controls and the data's latest refresh information together. For example, if a PDF has been produced for September, we should be able to establish whether it came from a source extract covering the complete month and which reporting selections were active. The draft file already includes the selected period and dimensions. A more developed version could also include a source-batch identifier, confirmed refresh timestamp and report version. Those details improve traceability, and they become particularly useful when a manager questions a figure several weeks after the report was produced. Without some record of the source and selections used, reproducing a historical output can be surprisingly difficult.

 

Taking the workflow further with PowerPoint

 

PDF is a convenient starting point because Excel can export a worksheet directly. PowerPoint introduces another possibility. Instead of producing a standalone report table, we could populate a management presentation containing a standard sequence of slides. One slide might show total performance, another might contain the department-by-month matrix, and another could present exceptions or important movements. VBA can control PowerPoint through its object model, making it possible to create presentations from templates, populate tables, update charts and save a draft deck.

 

The same design principle applies. Power Query would prepare the data, dynamic arrays would calculate the report and VBA would transfer the already-calculated results into the presentation. There is little reason for the PowerPoint automation to contain its own implementation of revenue aggregation or time intelligence - it should receive the results from the reporting calculation and concentrate on presenting them.

 

In a more developed system, a reporting workbook might therefore produce several output formats from the same validated dataset. An Excel report could preserve the interactive calculations and source detail, a PDF could provide a fixed record for management review and a PowerPoint deck could present selected KPIs and summaries in a more suitable format for meetings. These outputs would serve different purposes, but their numerical foundation would remain consistent. That consistency is one of the strongest arguments for separating calculation from presentation.

 

Designing for failure rather than assuming success

 

Our example has several potential failure points: the source file may be missing or inaccessible, Power Query may encounter an unexpected schema or data type, the reporting controls may be invalid, the calculation may return an error, a reconciliation may fail, the user may cancel the export or select a location where Excel cannot write the PDF. A reliable pipeline should treat these as normal possibilities, not as events that could never occur.

 

The appropriate response depends on the stage. If Power Query cannot retrieve the data, the refresh should not be treated as successful. If the data fails validation, the report should not be released for review as though it were reliable. If the PDF cannot be created, the macro should report the failure without damaging the source workbook or leaving behind a misleading output.

 

These concerns become particularly important when we begin combining several technologies. A failure in Power Query is not necessarily an Excel formula problem, the same way that a failed reconciliation is not necessarily a VBA problem. Separating responsibilities makes it easier to locate the source of an issue and it also allows us to improve individual stages without redesigning the entire process.

 

For example, the source might eventually move from an Excel export to a SQL database. That could require a different Power Query connection, but the loaded tblTransactions structure could remain unchanged and also the dynamic reporting engine and PDF-export procedure would not necessarily need any modification. Similarly, if management requests an additional output format, we could extend the presentation stage without rewriting the data acquisition process. This is the practical value of modular design.

 

How much automation is enough?

 

There is no particular virtue in automating a process beyond what its requirements justify. If a report is prepared once every quarter by one person, a Power Query refresh followed by a manual review and PDF export may be entirely adequate. If the same process is repeated every morning for several departments, it may justify a more automated workflow. At that point, we could introduce a controller procedure that refreshes the source data, waits for confirmed completion, checks the calculation and creates draft outputs. We could also maintain a processing log that records successful refreshes, failures, reporting periods and generated filenames.

 

But those features have a maintenance cost of their own as every additional automation step introduces another behaviour that must be tested. A particularly common mistake is to automate a poorly defined process before its business rules have been established. If the meaning of a valid transaction is still changing, the source data is inconsistent or the expected report results have not been verified, automation will not solve those problems - it may simply produce incorrect reports more quickly. That is why our sequence throughout this series has been useful. We developed the calculations first, established their business meaning, created ways to test them and only then considered automating the surrounding workflow. This is a much stronger foundation than beginning with a macro and gradually adding business rules to it.

 

A reporting pipeline, not a collection of competing calculations

 

We now have a clearer picture of how the technologies fit together: Power Query owns the process of acquiring and preparing structured source data, dynamic arrays own the reporting calculations, transformations and presentation-ready datasets, while VBA owns procedural actions such as creating snapshots, managing output files and coordinating interactions with other Office applications. The technologies are not competing to perform the same work - they are cooperating through clearly defined interfaces, and the most important of those interfaces is the Excel Table. Power Query produces tblTransactions in an agreed structure and the reporting calculation consumes that Table. The next interface is the dynamic report itself. The formula anchored at J10 produces a rectangular output whose dimensions may change but whose general structure is predictable. VBA consumes that result without needing to know how its numbers were calculated. The final interface is the output file. The PDF or PowerPoint presentation is a fixed representation of the validated report, ready for human review.

 

Each stage can be understood, tested and maintained separately. That is what makes the process a reporting pipeline rather than a large macro performing several unrelated tasks.

 

From individual automation to a reporting system

 

Looking back over the series, we started with fairly modest formula transformations. A dataset could be filtered, reshaped or enriched in one cell. That was already useful, but it was only the beginning. We then developed techniques for grouping, aggregation, time intelligence and dynamic reporting matrices. With LAMBDA, we began separating reusable business rules from individual reports. With MAKEARRAY, we generated outputs whose dimensions followed the reporting requirements rather than a predefined worksheet layout. We built a configurable reporting engine and examined how to validate its results, and now we have connected that engine to an operational workflow.

 

The source data can be refreshed through Power Query. The reporting calculation can produce the required management views. Validation checks can establish whether those results are suitable for review. VBA can then prepare static draft outputs without duplicating the underlying business logic. That is a substantial improvement over a workbook that depends on somebody copying data, extending formulas, formatting tables and manually preparing reports every month.

 

But it is also important to recognise the limits of what we have built. The current pipeline is still designed for one reporting workbook and a relatively straightforward source-data structure. A larger business might have several data sources, shared reference tables, multiple reporting outputs, historical adjustments and requirements for reproducible month-end results. At that point, some of the techniques we have developed would remain useful, but the overall architecture would need to become more deliberate. We would need to think about source-data versions, historical reporting periods, transaction corrections, reusable data models and how several reports can share one consistent definition of the underlying business information.

 

Those are not problems that require abandoning Excel. They do, however, require us to think beyond a single report, and that provides a natural direction for the next stage of the series. In the next post, we will examine how to design a shared reporting data model in Excel, allowing several related management reports to draw from consistent source tables, reference data and business rules without duplicating transformations throughout the workbook.

23 November 2026

Full Service Consulting

Reporting

Automation

Cat On A Spreadsheet

Cat On A Spreadsheet