My original code was for Excel 2010. It worked in that version. It failed when I tried to run it in Excel 2016.
I added a version checker that used that code for versions less that Excel 2016 and a different code for Excel 2016 and later. I therefore assumed that Excel 2013 would be happy with the 2020 version. This may not be the case.
I also used the sTextBoxName constant properly instead of having the hard coded name of the textbox in 5 different places.
If you are running Excel 2013 this might still error out.
Try the following code and let me know how it works and if there is a problem what version of Excel you are running.
Be sure to replace
Textbox 2 in the following line in 'Sub MoveTextboxOnPageBreak' to the name of the Textbox you are using.
Const sTextBoxName As String = "
Textbox 2" 'Change Textbox 2 to the name of the textbox that you want to keep off of the page break
VBA Code:
Option Explicit
Sub MoveTextboxOnPageBreak()
Dim aryBreaks As Variant
Const sTextBoxName As String = "Textbox 2" 'Change Textbox 2 to the name of the textbox that you want to keep off of the page break
Dim lTopLeftRow As Long
Dim lBottomRightRow As Long
Dim lIndex As Long
Dim lHBCount As Long
Dim lHBRow As Long
Dim x
With ActiveSheet
Set x = .Shapes(sTextBoxName)
.DisplayPageBreaks = True
aryBreaks = GetHorizPageBreaks
lHBCount = UBound(aryBreaks)
If lHBCount > 1 Then
'Might have to move box
lTopLeftRow = .Shapes(sTextBoxName).TopLeftCell.Row
lBottomRightRow = .Shapes(sTextBoxName).BottomRightCell.Row
For lIndex = 2 To lHBCount
lHBRow = aryBreaks(lIndex)
If lTopLeftRow < lHBRow And lBottomRightRow + 1 > lHBRow Then
'Horizontal Break is between top and bottom of textbox
.Shapes(sTextBoxName).Top = .Cells(lHBRow, 1).Top
Exit For
End If
Next
Else
'No horizontal break yet
End If
End With
End Sub
Function GetHorizPageBreaks()
'Return existing horizontal page breaks on the active sheet
Dim HPBrk As HPageBreak
Dim sType As String
Dim aryHBreaks As Variant
Dim lIndex As Long
'Note Automatic page breaks do not exist unless there is text that requires them
With ActiveSheet
If .HPageBreaks.Count > 0 Then
ReDim aryHBreaks(1 To .HPageBreaks.Count + 1)
aryHBreaks(1) = 1
If Val(Application.Version) < 16 Then
'Excel 2010
For Each HPBrk In .HPageBreaks
lIndex = lIndex + 1
'First row on new page
aryHBreaks(lIndex) = HPBrk.Location.Row
Next
Else
'Excel 2016
For lIndex = 2 To UBound(aryHBreaks)
aryHBreaks(lIndex) = .HPageBreaks(lIndex - 1).Location.Row
Next
End If
Else
ReDim aryHBreaks(1 To 1)
aryHBreaks(1) = 1
End If
End With
GetHorizPageBreaks = aryHBreaks
End Function