【问题标题】:VBA Excel page break at change in cell to every worksheet in the workbookVBA Excel分页符在单元格更改为工作簿中的每个工作表
【发布时间】:2017-09-27 21:16:53
【问题描述】:

我有一些代码可以在单元格内容更改时添加分页符,但是我无法让它运行超过活动工作表。我有大约 80 张纸需要运行它并且需要它同时运行。我曾尝试在 ThisWorkbook 上运行它,但它不起作用。它可以逐页显示,但不适用于整个工作簿。

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

【问题讨论】:

    标签: excel page-break vba


    【解决方案1】:

    有点草率的解决方案(因为你不应该真的使用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
    

    【讨论】:

    • @K.Davis 为什么要删除工作表?
    • @K.Davis 这与这个宏完全无关。 ws_count 每次都是动态创建的——这正是我们在这里使用 ws_count 而不是像 80 这样的静态数字的原因。
    • @K.Davis 我认为您误读了ThisWorkbook.Sheets(i).Activate 的效果 - Sheet name 是无关紧要的 - 这是按顺序遍历存在于工作簿。
    • 如果我有 5 张纸,分别命名为“Tim”、“Bob”、“Mary”、“Michael”和“Joe”,ThisWorkbook.Sheets(3).Name 将返回“Mary”。
    【解决方案2】:

    我将如何处理您的问题:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      相关资源
      最近更新 更多