It turns out that the HPageBreaks collection object (and the VPageBreaks as well) cannot be accessed via VBA if the worksheet in question is in page break preview mode.
I have modified the existing code.
Sub KeepRangeTogether()
Dim ws As Worksheet
Set ws = Worksheets("ORIGINAL") 'define worksheet
Excel.Application.ScreenUpdating = False
With ws
.ResetAllPageBreaks 'remove all manual page breaks
'(only needed if this code is run multiple times on the same sheet)
SetHorPageBreak .Range("A1:A20") 'define range you wish to keep together
SetHorPageBreak .Range("A21:A40") 'define range you wish to keep together
'
End With
Excel.Application.ScreenUpdating = True
End Sub
Public Sub SetHorPageBreak(ByVal argRange As Range)
Dim pb As HPageBreak, wb As Workbook, ws As Worksheet, vw As XlWindowView
Set wb = ActiveSheet.Parent
Set ws = ActiveSheet
argRange.Parent.Parent.Activate
argRange.Parent.Activate
vw = ActiveWindow.View
ActiveWindow.View = xlNormalView
For Each pb In argRange.Parent.HPageBreaks 'loop through all page breaks
If Not Intersect(pb.Location, argRange) Is Nothing Then 'if a page break intersects your RangeToKeep
argRange.EntireRow.PageBreak = xlPageBreakManual 'insert manual page break
Exit For
End If
Next pb
ActiveWindow.View = vw
wb.Activate
ws.Activate
End Sub
(I am coming from this thread: "conditionnal" Page break - How to simplify / shorten code)
Hi,
I am working on a contract creator and wanted to include that code, because it is very convinient. I am having some trouble making it fully work.
First off: The workbook has one input sheet and several other sheets which use the input information to be displayed in them. I'm calling with different buttons a row of serveral tasks, which are including reseting hidden rows, rehiding them according to the updates, selecting the necessary sheets and using the Application.CommandBars.ExecuteMso "PrintPreviewAndPrint" to print / save as pdf. One of the sheets, which is selected, is the where I want to implement that function. The sheet contains blocks of different terms, which vary in length according to the input. Empty rows will be hidden. Block range (for example A64:A71) stays the same all the time.
In my example only the first necessary page break is done and all the other are ignored.
Am I missing something?
Thanks in advance