问题描述
我正在尝试在 D 列中找到不同值的行上方插入一个分页符。我发现这段代码作为开始很有帮助。它正在搜索特定单词并在那里创建分页符。但是如果这个词并不总是被定义呢?有人可以帮助更新此代码或提供有关在找到不同值时如何创建分页符的反馈吗? 示例表如下。它应该在 D 列中每个不同的发票编号上方创建一个分页符。如果循环会更容易,也请帮忙。
Sub InsertPageBreakAtDifValue()
Dim x As Integer
Dim LR As Integer
LR = Cells(Rows.Count,1).End(xlUp).Row
For x = 1 To LR
If Cells(x,1).Value = "Invoice Total" Then
ActiveSheet.HPageBreaks.Add Before:=Rows(x + 1)
End If
Next
End Sub
行 | 价值 | 数量 | 发票 |
---|---|---|---|
10 | 100 | 10 | 12345 |
20 | 100 | 10 | 12345 |
30 | 100 | 10 | 12345 |
40 | 100 | 10 | 56789 |
50 | 100 | 10 | 56789 |
60 | 100 | 10 | 56789 |
70 | 100 | 10 | 78910 |
解决方法
首先确保数据范围按发票编号排序。
Dim invNo As Integer
Dim prevInvNo As Integer
prevInvNo = 0
For x = 1 to LR
invNo = Cells(x,1).Value
' if invoice number has changed...
if prevInvNo <> invNo then
' don't insert a page break before the first invoice number
if prevInvNo > 0 then
ActiveSheet.HPageBreaks.Add Before:=Rows(x + 1)
end if
prevInvNo = invNo
end if
next x