使用VBA插入分页符

时间:2018-08-01 12:11:12

标签: excel vba excel-vba

我正在尝试插入分页符,以允许每8行Excel表打印一次。我遇到的问题是,使用“ ActiveWindow.View = xlPageBreakPreview”方法时,第一个分页符发生在第10行之后,然后从那里开始,每8行出现一次。这是我当前正在使用的代码:

ActiveSheet.ResetAllPageBreaks
ActiveWindow.View = xlPageBreakPreview
ActiveSheet.VPageBreaks(2).DragOff Direction:=xlToRight, RegionIndex:=1
ActiveSheet.VPageBreaks(1).DragOff Direction:=xlToRight, RegionIndex:=1

With ActiveSheet.PageSetup
    .CenterHeader = "&""Chiller""&75WOC"
    .CenterFooter = "&""Chiller""&75 PLACARD"
    .PrintQuality = 600
    .CenterHorizontally = True
    .CenterVertically = True
    .Orientation = xlLandscape
    .PaperSize = xlPaperLetter
    .Zoom = 45
    .LeftMargin = Application.InchesToPoints(0)
    .RightMargin = Application.InchesToPoints(0)
    .TopMargin = Application.InchesToPoints(0.75)
    .BottomMargin = Application.InchesToPoints(0.75)
    .HeaderMargin = Application.InchesToPoints(0.3)
    .FooterMargin = Application.InchesToPoints(0.3)
End With

我尝试添加此循环以手动添加分页符,但它使代码陷入困境,所以我想知道是否有一个我不知道的简单解决方案。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以这样添加分页符:

Worksheets("Sheet1").HPageBreaks.Add Before:=Worksheets("Sheet1").Rows(25)
Worksheets("Sheet1").VPageBreaks.Add Before:=Worksheets("Sheet1").Columns("J")

Worksheets("Sheet1").Rows(25).PageBreak = xlPageBreakManual
Worksheets("Sheet1").Columns("J").PageBreak = xlPageBreakManual

要在第10行之后获得每8ᵗʰ行,请使用类似的循环

Dim iRow As Long
For iRow = 10 To LastRow Step 8
    'your page break code here
Next iRow

其中LastRow是最后使用的行,例如

Dim LastRow As Long
LastRow = Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row 'find last used row in column A

这样可能会导致结果:

Option Explicit

Public Sub AddPageBreaks()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") 

    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'find last used row in column A

    Dim iRow As Long
    For iRow = 10 To LastRow Step 8
        ws.HPageBreaks.Add Before:=ws.Rows(iRow)
        ws.Rows(iRow).PageBreak = xlPageBreakManual
    Next iRow
End Sub