所以我有一个宏,旨在为工作表的打印区域中的每个分页符插入 4 个标题行。当我在调试模式下逐步运行它时,它将为每个分页符插入正确的标题行,但是当它自行运行时,它似乎正在跳过部分。我添加了 Sleeps 和 Debug.Prints 以找出问题所在,但我仍然无法弄清楚。
这是代码:
Sub InsertRowPageBreak()
Dim WS As Worksheet
Dim rng As Range
Dim pb As Variant
Dim Row As Integer
Dim OffSet As Integer
Dim InsertRow As Integer
Set WS = ThisWorkbook.Worksheets(1)
WS.Activate
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Dim i As Integer
i = 1
For Each pb In WS.HPageBreaks
Debug.Print "Iteration: " & i
i = i + 1
Row = pb.Location.Row
Range("A" & Row).Select
Debug.Print "Page Break at Row: " & Row
If (Range("A" & Row - 2).Value Like "*Date*") Then
InsertRow = Row - 4
Range("A" & InsertRow).Select
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
Debug.Print "Inserting Page Break @ Row: " & InsertRow
Else
Sleep 150
InsertRow = Row - 1
Debug.Print "Inserting Row " & InsertRow
If (Range("D" & InsertRow).Value Like "*Compliment*") Then
Sleep 150
Sheets(2).Activate
Rows("1:4").Select
Selection.Copy
Sheets(1).Activate
Range("A" & InsertRow).Select
Selection.Insert Shift:=xlDown
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
Debug.Print "Inserted Header 1"
ElseIf (Range("D" & InsertRow).Value Like "*Complaint*") Then
Sleep 150
Sheets(2).Activate
Rows("5:8").Select
Selection.Copy
Sheets(1).Activate
Range("A" & InsertRow).Select
Selection.Insert Shift:=xlDown
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
Debug.Print "Inserted Header 2"
ElseIf (Range("D" & InsertRow).Value Like "*Question*") Then
Sleep 150
Sheets(2).Activate
Rows("9:12").Select
Selection.Copy
Sheets(1).Activate
Range("A" & InsertRow).Select
Selection.Insert Shift:=xlDown
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
Debug.Print "Inserted Header 3"
End If
Sleep 250
End If
Sleep 250
Next pb
End Sub
当我在调试模式下运行它时,Debug.Print 打印出来
Iteration: 1
Page Break at Row: 33
Inserting Row 32
Inserted Header 1
Iteration: 2
Page Break at Row: 66
Inserting Row 65
Inserted Header 1
Iteration: 3
Page Break at Row: 94
Inserting Row 93
Inserted Header 2
Iteration: 4
Page Break at Row: 119
Inserting Row 118
Inserted Header 3
当它自己运行时
Iteration: 1
Page Break at Row: 33
Inserting Row 32
Inserted Header 1
Iteration: 2
Page Break at Row: 35
Inserting Row 34
Iteration: 3
Page Break at Row: 92
Inserting Row 91
Inserted Header 2
Iteration: 4
Page Break at Row: 94
Inserting Row 93
任何建议或帮助将不胜感激。
谢谢,凯文