Andrew Hammond
Andrew Hammond

Reputation: 11

How can I Conditionally Insert Rows after Page Breaks in Excel VBA?

I am currently attempting to write a macro that Inserts a "Title continued" and a "Subtitle continued" row at the top of each new page, when appropriate. To do this, I want to loop through every row and determine:

  1. Is the row a page break that is not a title or subtitle (if so, a row insert "Title continued" and another row "Subtitle continued"),
  2. Is the row a page break and already a subtitle (if so, only insert "Title continued"),
  3. Is the row already a title or not a page break (if so, skip),

Currently for every row except the subtitles and titles themselves, the subtitle and title are stored in columns C and D respectively. For the title and subtitle rows, columns C and D are blank. The issue that I am coming across is that I am getting weird shifting after the first insert occurs. Most row inserting macros go backwards, but that won't work here because the page breaks will change after inserting rows before the break. Here is the code I have written:

Inserts = 0
Dim Counter As Long
Counter = 1
While Counter < RowCount
    If Rows(Counter).PageBreak <> -4142 And Cells(Counter, "C").Value <> "" Then
        Range("C" & (Counter), "C" & (Counter + 1)).EntireRow.Insert
        Cells(Counter, "A").Value = UCase(Cells(Counter + 2, "D").Value) & " continued"

        Cells(Counter + 1, "A").Value = UCase(Cells(Counter + 2, "C").Value) & " continued"

        Counter = Counter + 3
        Inserts = Inserts + 2
    ElseIf Rows(Counter).PageBreak <> -4142 And Cells(Counter + 1, "C").Value <> "" Then
        Range("C" & Counter).EntireRow.Insert
            Cells(Counter, "A").Value = UCase(Cells(Counter + 2, "D").Value) & " continued"

        Counter = Counter + 2
        Inserts = Inserts + 1
    Else: Counter = Counter + 1
    End If
Wend
RowCount = RowCount + Inserts - 2

Thanks!

Andy

Upvotes: 0

Views: 1135

Answers (1)

Andrew Hammond
Andrew Hammond

Reputation: 11

Update: This code actually does work as intended. The issue was that other columns in the spreadsheet were affecting the page breaks even though they were out of the print range. I deleted those columns in the code after this segment was run, so the page breaks shifted afterwards, giving the impression that this portion didn't work. Setting all automatic page breaks to xlPageBreakManual solved the issue without forcing me to delete the columns early (as I needed their data).

Upvotes: 1

Related Questions