在分页符预览中自动插入分页符

时间:2019-02-28 09:25:56

标签: excel vba

我具有根据C列中的部分自动插入分页符的代码。

我的部分分为4行。

enter image description here

这是有时在节位于B列中时现在可以使用的代码,现在节位于C列中,并且我更改了范围,但它似乎不起作用:

var myValue = $(this).data()[“value”]
switch (myValue) {
    case “oneValue”:
        // do something
        break;
    case “otherValue”:
        // do something else
        break;
}

在进行包装和自动调整之前,

Dim fnd As Range, r As Range, pb As Variant
Dim PrintVersion As Worksheet

Set PrintVersion = ThisWorkbook.Sheets("Print version")

PrintVersion.Activate

   ' make sure sheet is in page break view
    PrintVersion.Parent.Windows(1).View = xlPageBreakPreview

    ' first clear any set page breaks
    On Error Resume Next
    For Each pb In PrintVersion.HPageBreaks
        pb.Delete
    Next
    On Error GoTo 0

    ' move preposed breaks to top of segement
    With PrintVersion.HPageBreaks
        For pb = 1 To .Count
            Set r = Cells(.Item(pb).Location.Row, 3)
            Set fnd = Range("C:C").Find("*", r, , , , xlPrevious)
            If Not Intersect(fnd.Offset(, -1).Resize(fnd.Offset(, 1).End(xlDown).Row - fnd.Row + 1, 4), r) Is Nothing Then
                Set .Item(pb).Location = fnd
            DoEvents
        End If
        Next
    End With

结果(分页符应在第148行上):

enter image description here

1 个答案:

答案 0 :(得分:1)

我建议在第一列中将所有分页符重置为ResetAllPageBreaks,并重置为Find

Private Sub BreakPages()
    Dim fnd As Range, r As Range, pb As Variant
    Dim PrintVersion As Worksheet

    Set PrintVersion = ThisWorkbook.Sheets("Print version")

    PrintVersion.Activate

    ' make sure sheet is in page break view
    PrintVersion.Parent.Windows(1).View = xlPageBreakPreview

    ' first clear any set page breaks
    PrintVersion.ResetAllPageBreaks

    ' move preposed breaks to top of segement
    With PrintVersion.HPageBreaks
        For pb = 1 To .Count
            ' check if first column is empty
            Set r = PrintVersion.Cells(.Item(pb).Location.Row, 1)
            If r.value = "" Then
                ' find previous cell in column 1 which is not empty
                Set fnd = PrintVersion.Columns(1).Find("*", r, , , , xlPrevious)
                ' set page break 1 row above it
                Set .Item(pb).Location = fnd.Offset(-1, 0)
                DoEvents
            End If
        Next
    End With
End Sub