I am working on a project wherein I read a CSV file, format data in a temporary sheet (OutputSheet
), copy-paste the formatted data on a sheet to be printed (PrintSheet
), save the PrintSheet as PDF after inserting manual page breaks so that a block of data is not split across pages.
I do this in an Excel VBA Macro function. Here is the relevant part of the code:
PrevPageNum = PrintSheet.HPageBreaks.Count
OutputSheet.Rows("6:" & (CurrHistoryRows + 14)).Copy
PrintSheet.Cells(PrtPstStRow, 1).PasteSpecial Paste:=xlPasteFormats
PrintSheet.Cells(PrtPstStRow, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
PageNum = PrintSheet.HPageBreaks.Count
If PrevPageNum < PageNum Then
PrintSheet.Rows(PrtPstStRow).PageBreak = xlPageBreakManual
End If
When I call the Macro directly from within the code or from an assigned button in Quick Access toolbar the Manual Page breaks are assigned correctly. But when I call this Macro from Auto_Open these are not assigned at all (everything else remaining the same!). Upon debugging the code, I noticed that PrevPageNum
and PageNum
are always zero when the macro is called from Auto_Open
. In other two case the values change.
Also would like to mention that PrintSheet
has width scaled to 1 Page
in the Page Layout.
Any ideas please! Thank you.
Update:
I added these statements just before PrintSheet.HPageBreaks.Count
and the Page Breaks started working from Auto_Open
as well.
OutputSheet.Activate
PrintSheet.Activate
FINAL Update:
When I ran this on a "slow" computer (processor - i3 with 3GB DDR2 RAM) then again I faced the same issue of Page Breaks being skipped. After much looking around finally I found a solution (or a workaround) having 100% success rate.
You need to scroll vertically to the last used row so that HPageBreaks Collection
gets refreshed with the Count
. Final Code as follows:
PrintSheet.Activate
CurrentRowNum = ActiveWindow.ScrollRow
ActiveWindow.ScrollRow = 5000 'or the last used row
PageNum = PrintSheet.HPageBreaks.Count
ActiveWindow.ScrollRow = CurrentRowNum