将最近的自动水平分页符移动到关键字行

时间:2017-07-19 14:13:36

标签: excel-vba vba excel

我正在尝试清理自动水平分页符落在我的工作表上的方式。如果自动分页符没有超出短语"总体状态"在专栏中' D'我想将下一个最接近的水平分页点移到"总体状态"起来。下面是一个代码片段,它将水平分页符放在所有行上,表示"总体状态"在D列中,但这是太多的分页符。

Sub Pagebreak()
'adds horizontal pagebreak before every 'Overall Status'

Dim Search As String

Search = "Overall Status"

With ActiveSheet.UsedRange
    Set c = .Find(What:=Search, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True)
    If Not c Is Nothing Then
        FirstAddress = c.Address
        Do
            ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=c
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> FirstAddress
    End If

    'Then try toggle between pagebreak screen and normal view
    End With
End Sub

下面的代码片段显示了当前水平分页符的当前位置:

Sub HPageBreakTest()
'counts and shows where horizontal pagebreaks are
Dim pgeBreak As HPageBreak

With ActiveSheet
.Cells(65536, 1).Select
MsgBox .HPageBreaks.Count & " Horizontal page breaks counted"
For Each pgeBreak In .HPageBreaks
MsgBox "pgbreak at row: " & pgeBreak.Location.row
.Cells(65536, 1).Select
Next pgeBreak
.Cells(1, 1).Select
End With

End Sub

我想弄清楚如何将这两个代码片段的逻辑结合起来,以(1)找到下面的第一个自动水平分页符&#34;总体状态&#34; (2)将该页面分解为&#34;总体状态&#34; D列中的短语。不是每个&#34;总体状态实例的水平分页符。&#34;我希望我的问题有道理。感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

啊,我建议的更改会在第一次出现&#34;整体状态&#34;时插入分页符。在第一次自然分页之前。您希望在分页符之前的最后一次出现之前插入。复杂的是,只要您输入手动分页符,所有其他分组就会发生变化。 因此,遍历第一页的范围以查找最后一次出现 插入分页符 重复所有其他页面

页面n中D列的范围由最后一页分隔符的行+1给出下一页分隔符的行所以

 Dim Search As String
 Search = "Overall Status"
 Dim x as long
 Dim r as range
 dim lastrow as long

 with activesheet
     do while x < .hpagebreaks.count
           for each r in range("D" & (lastrow+1) & ":D" & .HPageBreaks(x+1).Location.Row)
              if r = search then     'might have found it
                  lastrow = r.row  'so remember the row number
              end if
           next r
           if lastrow = 0 then exit sub  'no find  
           .hpagebreaks.add before:=range("A" & lastrow)

           x = x +1
      loop
 end with

答案 1 :(得分:0)

替换

 With ActiveSheet.UsedRange

 With Activesheet.range("D1:D" & HPageBreaks(1).Location.Row)

(注意这假设至少有一个分页符)