The ExcelTemplate method of creating Excel files is to design a template in Excel that contains data markers. Data markers are cell values that begin with %%= or %%=$ that specifies a database column, variable, or array to insert into the spreadsheet column. ExcelWriter does this by inserting a new row into the worksheet for each row of data being imported. This means that anything below the data marker in the template will be pushed down as the new rows of data are imported.
Data markers from the same data set can be placed next to each other, but placing data markers from different data sets side-by-side in an ExcelTemplate can cause extra rows to be inserted into the smaller data sets.
This series of posts explains how to get rid of the extra rows in output files that result from placing data markers side by side. If you’re not a current ExcelWriter user, you can download a free evaluation and follow along!
Part 3: Putting it together
For each named range in the workbook, UpdateRange() will need to be called. For each group of side-by-side data markers, ClearBadDisplay() will need to be called. I put UpdateRange() and ClearBadDisplay() in a module and called the following code in the WorkbookOpen() event:
For testing purposes, hotkeying this to an ActiveX button is really useful.
This code only deals with the contents of the ranges, not the formatting. In order to preserve the formating:
- Format the data marker cells on the hidden page.
- Change the UpdateRange()code to copy the source range and paste it into the displayed range:
- Change the ClearBadDisplay()method to clear the formatting as well as the contents:
Since the PasteSpecial() method actually tells Excel to select the source range, make a copy, select the destination range, and paste it into the new range, it can look unnerving when opening the document (since these Excel actions literally flash by on the screen). The customer did not mind and was happy with the result.
You can also use this workaround with charts. Just set the data source of the chart to point to the data range on the hidden sheet instead of the display sheet.