Hello,
I have a piece of code designed to place horizontal page breaks so the heading for a group of data isn't by itself at the bottom of a page. However, it throws a run-time error 9 - subscript out of range.
This appears to be a known issue, but Microsoft's solution, to select the last cell first, doesn't seem to be working, unless I'm misunderstanding what they said. Has anyone experienced this or have any ideas about how to fix it?
Disclaimer: I'm aware there are a lot of "selects" in my code - they're from attempts at debugging and haven't been removed yet.
I have a piece of code designed to place horizontal page breaks so the heading for a group of data isn't by itself at the bottom of a page. However, it throws a run-time error 9 - subscript out of range.
This appears to be a known issue, but Microsoft's solution, to select the last cell first, doesn't seem to be working, unless I'm misunderstanding what they said. Has anyone experienced this or have any ideas about how to fix it?
Disclaimer: I'm aware there are a lot of "selects" in my code - they're from attempts at debugging and haven't been removed yet.
Code:
Dim rg1 as Range
Dim scrollRow as Long
Dim scrollColumn as Long
Dim rgPrintArea as Range
Dim lastrow as Range, lastcol as Range, LastCell as Range
Dim i as Long, j as Long
On Error GoTo 0
Application.EnableEvents = False
With Sheets("FoE")
Set rg1 = ActiveCell
scrollRow = ActiveWindow.scrollRow
scrollColumn = ActiveWindow.scrollColumn
Set rgPrintArea = Intersect(.Range(.PageSetup.PrintArea), .UsedRange)
.ResetAllPageBreaks
.PageSetup.Zoom = False
.PageSetup.FitToPagesWide = 1
.PageSetup.FitToPagesTall = False
ActiveWindow.View = xlPageBreakPreview
.DisplayAutomaticPageBreaks = True
Set lastrow = rgPrintArea.Find(What:="*", After:=rgPrintArea.Cells(1, 1), LookIn:=xlValues, lookat:=xlPart, searchorder:=xlByRows, searchdirection:=xlPrevious)
Set lastcol = rgPrintArea.Find(What:="*", After:=rgPrintArea.Cells(1, 1), LookIn:=xlValues, lookat:=xlPart, searchorder:=xlByColumns, searchdirection:=xlPrevious)
Set LastCell = Cells(lastrow.Row, lastcol.Column)
LastCell.Select
If .HPageBreaks.Count > 0 Then
Do
i = i + 1
'The following line is where it throws the subscript out of range error:
.HPageBreaks(i).Location.EntireRow.Select
j = Selection.Row
If .Cells(j - 1, 2).Interior.Color = RGB(191, 191, 191) Then
.Cells(j - 1, 2).EntireRow.Select
j = Selection.Row
If .Cells(j - 1, 2).Interior.Color = RGB(191, 191, 191) Then
.Cells(j - 1, 2).EntireRow.Select
j = Selection.Row
End If
End If
LastCell.Select
If j <> .HPageBreaks(i).Location.Row Then
Set .HPageBreaks(i).Location = .Cells(j, 2)
End If
If i >= .HPageBreaks.Count Then Exit Do
Loop
End If
rg1.Select
ActiveWindow.scrollRow = scrollRow
ActiveWindow.scrollColumn = scrollColumn
ActiveWindow.View = xlNormalView
End With
Application.EnableEvents = True