gpt4 book ai didi

Excel 宏在调试中有效,但在完整运行中无效

转载 作者:行者123 更新时间:2023-12-03 02:09:53 26 4
gpt4 key购买 nike

所以我有一个宏,旨在为工作表打印区域中的每个分页符插入 4 个标题行。当我在 Debug模式下逐步运行它时,它会为每个分页符插入正确的标题行,但是当它单独运行时,它似乎会跳过某些部分。我添加了 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模式下运行它时,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

任何建议或帮助将不胜感激。

谢谢,凯文

最佳答案

插入 Pagebreak 后,Excel 需要重新分页才能更新 HPageBreaks 集合。

为了允许 Excel 在代码运行时执行此操作,请使用 DoEvents 代替 Sleep

关于Excel 宏在调试中有效,但在完整运行中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com