Hello, I use this code to insert a page break before a selected range if the said range is split over 2 sheets. However, I have multiple ranges (12 to 15), to which I'd like to apply the same code. There must be a way to simplify / shorten the code, but I don't know how. I've put 3 ranges in my example code but there will be a dozen.
Thank you for your time
Thank you for your time
VBA Code:
Option Explicit
Sub KeepRangeTogether()
Dim Ws As Worksheet
Set Ws = Worksheets("Feuil3") 'define worksheet
Dim RangeToKeep As Range
Set RangeToKeep = Ws.Range("A17:A28") 'define range you wish to keep together
Dim RangeToKeep2 As Range
Set RangeToKeep2 = Ws.Range("A58:A70") 'define range you wish to keep together
Dim RangeToKeep3 As Range
Set RangeToKeep3 = Ws.Range("A100:A115") 'define range you wish to keep together
Ws.ResetAllPageBreaks 'remove all manual page breaks
'(only needed if this code is run multiple times on the same sheet)
Dim pb As HPageBreak
For Each pb In Ws.HPageBreaks 'loop through all page breaks
If Not Intersect(pb.Location, RangeToKeep) Is Nothing Then 'if a page break intersects your RangeToKeep
RangeToKeep.EntireRow.PageBreak = xlPageBreakManual 'insert manual page break
Exit For
End If
Next pb
For Each pb In Ws.HPageBreaks 'loop through all page breaks
If Not Intersect(pb.Location, RangeToKeep2) Is Nothing Then 'if a page break intersects your RangeToKeep
RangeToKeep2.EntireRow.PageBreak = xlPageBreakManual 'insert manual page break
Exit For
End If
Next pb
For Each pb In Ws.HPageBreaks 'loop through all page breaks
If Not Intersect(pb.Location, RangeToKeep3) Is Nothing Then 'if a page break intersects your RangeToKeep
RangeToKeep3.EntireRow.PageBreak = xlPageBreakManual 'insert manual page break
Exit For
End If
Next pb
End Sub