VBA Excel 工作簿中每个工作表的单元格更改处的分页符

VBA Excel page break at change in cell to every worksheet in the workbook

我有一些代码可以在单元格内容发生变化时添加分页符,但是我无法将其设置为 运行 超过活动 sheet。我有大约 80 sheets 我需要 运行 这个,同时需要它 运行。我已在 ThisWorkbook 上尝试 运行ning 它,但它不起作用。它在 sheet 乘 sheet 的基础上效果很好,但不是在整个工作簿上。

Option Explicit

Sub Set_PageBreaks()

    Dim lastrow As Long, c As Range

    lastrow = Cells(Rows.Count, "B").End(xlUp).Row

    Application.ScreenUpdating = False

    For Each c In Range("A2:A" & lastrow)
        If c.Offset(1, 0).Value <> c.Value And c.Offset(1, 0) <> "" Then
            c.Offset(1, 0).PageBreak = xlPageBreakManual
        End If
    Next c

    Application.ScreenUpdating = True

End Sub

有点草率的解决方案(因为你不应该真正使用 activate),但这应该可行:

Option Explicit
Sub Set_PageBreaks()

Application.ScreenUpdating = False

Dim ws_count As Long, i as long, lastrow As Long, c As Range
ws_count = ThisWorkbook.Worksheets.Count

For i = 1 to ws_count

    ThisWorkbook.Sheets(i).Activate

    lastrow = Cells(Rows.Count, "B").End(xlUp).Row

    For Each c In Range("A2:A" & lastrow)
        If c.Offset(1, 0).Value <> c.Value And c.Offset(1, 0) <> "" Then
            c.Offset(1, 0).PageBreak = xlPageBreakManual
        End If
    Next c

Next i

Application.ScreenUpdating = True
End Sub

以下是我将如何处理您的问题:

Option Explicit

Sub Set_PageBreaks()

    Dim Sheet As Worksheet, C As Range, lastrow As Long

    Call SpeedUpCode(True)

    For Each Sheet In ThisWorkbook.Sheets
        lastrow = Cells(Rows.Count, "B").End(xlUp).Row
        For Each C In Range("A2:A" & lastrow)
            If C.Offset(1, 0).Value <> C.Value And C.Offset(1, 0) <> "" Then
                C.Offset(1, 0).PageBreak = xlPageBreakManual
            End If
        Next C
    Next Sheet

    Call SpeedUpCode(False)

End Sub

Sub SpeedUpCode(ByVal Value As Boolean)
    With Application
        If Value = True Then
            .ScreenUpdating = False
            .Calculation = xlCalculationManual
        ElseIf Value = False Then
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
        End If
    End With
End Sub