Sub KeepTogether()
Dim HPB, CHbr As Long, I As Long, J As Long
Dim HBPrePost(), reFor As Boolean
'
Call ResetHB 'Remove
Application.ScreenUpdating = False
ActiveWindow.View = xlPageBreakPreview
reLoop:
For J = 1 To ActiveSheet.HPageBreaks.Count
CHbr = ActiveSheet.HPageBreaks(J).Location.Row
I = 0
If Cells(CHbr, "A") <> "" Then
If Cells(CHbr - 1, "A") <> "" Then
For I = CHbr - 1 To 1 Step -1
If Cells(I, 1) = "" Then Exit For
Next I
End If
If I > 1 And I < (CHbr - 1) Then
ActiveWindow.ActiveSheet.HPageBreaks.Add Before:=Rows(I + 1)
Cells(I + 1, 1).Value = 10
reFor = True
End If
End If
If reFor Then Exit For
Next J
If reFor Then reFor = False: GoTo reLoop
Application.ScreenUpdating = True
ActiveWindow.View = xlNormalView
MsgBox ("Grouping completed")
End Sub
Sub ResetHB()
ActiveWindow.View = xlPageBreakPreview
ActiveWindow.View = xlNormalView
For J = ActiveSheet.HPageBreaks.Count To 1 Step -1
CHbr = ActiveSheet.HPageBreaks(J).Location.Row
If Cells(CHbr, 1).Value = 10 Then
ActiveSheet.HPageBreaks(J).Delete
' ActiveSheet.HPageBreaks(3).Delete
Cells(CHbr, 1).Value = 1
End If
Next J
End Sub