我有一个由“作者”订购的清单。我正在尝试编写代码以插入分页符,以便我可以为每个作者打印出一个列表。
这是我编写的代码,它通过并选择了我想要分页的正确单元格,但由于某种原因它只是不插入中断。我没有收到任何错误,只是没有插入中断。
Sub addpagebreaksatvalue()
Dim x As Integer
Dim LR As Integer
Dim Fname As String
LR = Cells(rows.Count, 1).End(xlUp).Row
Fname = Cells(2, 5)
For x = 3 To LR
If Cells(x, 5) <> Fname Then
ActiveWindow.View = xlPageBreakPreview
Cells(x, 1).Select
ActiveWindow.SelectedSheets.HPageBreaks.Add before:=ActiveCell.Offset(0, 0)
Fname = Cells(x, 5)
Else: Fname = Cells(x, 5)
End If
Next
End Sub
答案 0 :(得分:0)
对您的代码进行了一些小的更改,请参阅其中的注释:
Sub addpagebreaksatvalue()
Dim x As Long
Dim LR As Long
Dim Fname As String
'Need to declare the object to work with
'previously was affecting whatever sheet was active
With ThisWorkbook.Sheets("Sheet1") 'change name of sheet as required
Application.Goto .Cells(1), 1
ActiveWindow.View = xlPageBreakPreview 'moved out the loop just needed once
ActiveSheet.ResetAllPageBreaks 'reset prior page breaks
LR = .Cells(.Rows.Count, 1).End(xlUp).Row
Fname = .Cells(2, 5)
For x = 3 To LR
If .Cells(x, 5) <> Fname Then
'no need to select the cell
ActiveWindow.SelectedSheets.HPageBreaks.Add before:=.Cells(x, 1)
Fname = .Cells(x, 5)
End If: Next: End With
'reset back the window view
ActiveWindow.View = xlNormalView
End Sub
答案 1 :(得分:0)
我试过这个(我选择整行而不仅仅是单元格):
Sub addpagebreaksatvalue()
Dim x As Integer
Dim LR As Integer
Dim Fname As String
Dim HPBreak As HPageBreak
LR = Cells(rows.Count, 1).End(xlUp).Row
Fname = Cells(2, 5)
For x = 3 To LR
If Cells(x, 5) <> Fname Then
ActiveWindow.View = xlPageBreakPreview
For Each HPBreak In ActiveSheet.HPageBreaks
If HPBreak.Location.Row = x Then Exit For
Cells(x,1).EntireRow.Select
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
Next
Fname = Cells(x, 5)
Else: Fname = Cells(x, 5)
End If
Next
ActiveWindow.View = xlNormalView
End Sub