I’m trying to insert page break in a Word document with using VBA. But I don’t know why page break only inserted before Page 2 instead of the whole document. Could anyone help? Thank you!
ABC Company Page 1
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
<When «Page» is found, insert page break here>
ABC Company Page 2
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
<When «Page» is found, insert page break here>
ABC Company Page 3
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Code:
Dim word As Object, doc As Object Set word = CreateObject("word.application") word.Visible = True word.Documents.Open ("c:report.txt") With Selection .PageSetup.Orientation = wdOrientLandscape .PageSetup.LeftMargin = InchesToPoints("0.5") .PageSetup.RightMargin = InchesToPoints("0.5") .Font.Size = 9 End With Selection.MoveDown unit:=wdParagraph, Count:=1 With Selection.Find .Forward = True .Text = "Page" .Replacement.Text = "" .Wrap = wdFindContinue .Execute If Selection.Find.Found = True Then Selection.StartOf unit:=wdParagraph Selection.Collapse Direction:=wdCollapseEnd Selection.InsertBreak (wdPageBreak) Selection.MoveDown unit:=wdParagraph, Count:=1 End If End With
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Selection.InsertBreak method (Word) |
vbawd10.chm158662778 |
vbawd10.chm158662778 |
word |
Word.Selection.InsertBreak |
2c9d8cb8-1cc1-3d69-1e26-3a6878c0b1da |
06/08/2017 |
medium |
Selection.InsertBreak method (Word)
Inserts a page, column, or section break.
Syntax
expression. InsertBreak
( _Type_
)
expression Required. A variable that represents a Selection object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Type | Required | WdBreakType | the type of break to insert. The default value is wdPageBreak. Some of the WdBreakType constants may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed. |
Remarks
When you insert a page or column break, the break replaces the selection. If you don’t want to replace the selection, use the Collapse method before using the InsertBreak method.
[!NOTE]
When you insert a section break, the break is inserted immediately preceding the selection.
Example
This example inserts a continuous section break immediately preceding the selection.
Selection.InsertBreak Type:=wdSectionBreakContinuous
See also
Selection Object
[!includeSupport and feedback]
- Remove From My Forums
-
Question
-
I’ve created a new Word document using Visual Basic. I would just like to know how to insert a page break using Visual Basic.
Thanks in advance,
Jim
James Hutchinson
Answers
-
You could use code like:
With ActiveDocument.Paragraphs(3).Range
.Collapse wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
Cheers
Paul Edstein
[MS MVP — Word]-
Proposed as answer by
Tuesday, April 5, 2016 9:19 AM
-
Marked as answer by
Deepak Saradkumar PanchalMicrosoft contingent staff
Tuesday, April 5, 2016 9:19 AM
-
Proposed as answer by
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
Option Explicit Const FIRST_ROW& = 28 Const FIRST_COL$ = "J" Const LAST_COL$ = "P" Const ITOGO_COL$ = "I" Sub CreatePageSubtotals() Dim iPageNum&, viewState, hpb As HPageBreak, iRow1&, iRow2& Dim count_pages As Variant Dim totalRow As Variant Dim a As Integer Dim fl As Boolean Dim rowI As Integer Dim R As Range, zoom Dim wR As Range, Row As Range, C As Range, _ HrAlg, CurH, NewH Dim Ar As Range Dim breakcount As Integer Dim temp As Double breakcount = ActiveSheet.HPageBreaks.Count Dim CountPages As Integer '????? ?????????? ??????? ??? ?????? Dim CountRow As Integer '????? ?????????? ????? Dim CountCol As Integer '????? ?????????? ???????? Dim Count1 As Integer '?????????? ??????? ?? ????????? Dim Count2 As Integer '?????????? ??????? ?? ??????????? Dim CountLastPageRow As Integer '????? ?????? ?????? ????? ????????????? ???????? ?? ????????? Dim CountLastPageCol As Integer '????? ??????? ?????? ????? ????????????? ???????? ?? ??????????? CountPages = Worksheets(1).PageSetup.Pages.Count CountRow = ActiveCell.SpecialCells(xlCellTypeLastCell).Row CountCol = ActiveCell.SpecialCells(xlCellTypeLastCell).Column Count1 = ActiveSheet.HPageBreaks.Count Count2 = ActiveSheet.VPageBreaks.Count CountLastPageRow = ActiveSheet.HPageBreaks(ActiveSheet.HPageBreaks.Count).Location.Row - 1 CountLastPageCol = ActiveSheet.VPageBreaks(ActiveSheet.VPageBreaks.Count).Location.Column - 1 If Count2 = 1 Then If Count1 > 1 Then If (CountRow - CountLastPageRow) < 23 Then ActiveSheet.HPageBreaks.Add Before:=Cells(CountLastPageRow - 5, 1) End If End If Else End If breakcount = ActiveSheet.HPageBreaks.Count 'Stop rowI = 0 'zoom = ActiveSheet.PageSetup.zoom 'ActiveSheet.ResetAllPageBreaks 'ActiveSheet.PageSetup.zoom = zoom Set R = Range("ÈòîãèÏîäïèñè") Set R = R.Offset(-1, 0).Resize(R.Rows.Count + 1, R.Columns.Count) R.Rows.PageBreak = xlPageBreakNone For Each wR In R.Rows If wR.PageBreak = xlPageBreakAutomatic Then 'R.Rows.PageBreak = xlPageBreakManual rowI = R.Rows.Row 'rowI = 1 End If Next ' ' àâòîôèò 'Application.ScreenUpdating = False 'Application.EnableEvents = False 'Application.Calculation = xlCalculationManual ' ' ' ' totalRow = Range("totalRow").Row ' ' Set R = Range("B24:B" & totalRow - 1) ' ' Set wR = Application.Intersect(R, R.Worksheet.UsedRange) ' ' For Each Row In wR.Rows ' CurH = Row.RowHeight ' NewH = CurH ' For Each C In Row.Cells ' If C.MergeCells And C.WrapText And C.Column = C.MergeArea.Column Then ' Set Ar = C.MergeArea ' HrAlg = C.HorizontalAlignment ' Ar.MergeCells = False ' Ar.HorizontalAlignment = xlCenterAcrossSelection ' Ar.Rows.AutoFit ' If NewH < Ar.RowHeight Then ' NewH = Ar.RowHeight ' End If ' Ar.MergeCells = True ' Ar.HorizontalAlignment = HrAlg ' End If ' Next ' Row.RowHeight = NewH ' Next totalRow = Range("totalRow").Row fl = False For a = 28 To totalRow Cells(a, 10).Value = Cells(a, 10).Value Cells(a, 11).Value = CDbl(Cells(a, 11).Value) Cells(a, 13).Value = CDbl(Cells(a, 13).Value) Cells(a, 15).Value = CDbl(Cells(a, 15).Value) Cells(a, 16).Value = CDbl(Cells(a, 16).Value) Next count_pages = ActiveWorkbook.Sheets.HPageBreaks.Count + 1 If count_pages = 1 Then Exit Sub End If totalRow = Range("totalRow").Row viewState = ActiveWindow.View ActiveWindow.View = xlPageBreakPreview iRow1 = FIRST_ROW For Each hpb In ActiveSheet.HPageBreaks iPageNum = iPageNum + 1 iRow2 = hpb.Location.Row - 1 If iRow2 >= totalRow + 20 Then fl = True Exit For End If If iRow2 >= totalRow Then iRow2 = rowI End If ' If iRow2 = R.Rows.Row - 1 Then ' R.Rows.PageBreak = xlPageBreakNone ' End If Rows(iRow2).Insert Rows(iRow2 + 1).PageBreak = xlPageBreakManual Cells(iRow2, ITOGO_COL) = "Èòîãî ïî ñòðàíèöå " & iPageNum & ":" 'Cells(iRow2, "J") = "Èòîãî ïî ñòðàíèöå " & iPageNum & ":" Range(Cells(iRow2, FIRST_COL), Cells(iRow2, LAST_COL)).FormulaR1C1 = _ "=SUBTOTAL(9,R[" & iRow1 - iRow2 & "]C:R[-1]C)" Rows(iRow2).Font.Bold = True Rows(iRow2).Font.Size = 6 Range("I" & iRow2).Select With Selection .Font.Size = 6 .HorizontalAlignment = xlRight End With Cells(iRow2, 12).Value = "X" Cells(iRow2, 14).Value = "X" iRow1 = iRow2 + 1 Next If fl = False Then 'Cells(iRow2, 11).Value = "X" Cells(iRow2, 12).Value = "X" Cells(iRow2, 14).Value = "X" iRow2 = totalRow + iPageNum Rows(iRow2).Insert Cells(iRow2, ITOGO_COL) = "Èòîãî ïî ñòðàíèöå " & iPageNum + 1 & ":" With Range(Cells(iRow2, FIRST_COL), Cells(iRow2, LAST_COL)) .FormulaR1C1 = "=SUBTOTAL(9,R[" & iRow1 - iRow2 & "]C:R[-1]C)" .NumberFormat = "0.00" End With Range(iRow2 & ":" & iRow2 + 1).Font.Bold = True Range(iRow2 & ":" & iRow2 + 1).Font.Size = 6 Range("I" & iRow2).Select With Selection .Font.Size = 6 .HorizontalAlignment = xlRight End With Cells(iRow2, 12).Value = "X" Cells(iRow2, 14).Value = "X" 'Cells(iRow2, 14).Value = "X" End If ' --> ïîäìåíà äàííûõ â ôóòåðå. Äîáàâëåíî À. Æàëóäêîâûì ActiveSheet.PageSetup.RightFooter = "Ñòðàíèöà " & "&P" & " Òîâàðíàÿ íàêëàäíàÿ ¹ " & Cells(23, 6).Value & " îò " & Cells(23, 8).Value ' <-- Âñòàâêà ëîãèêè îáðàáîòêè ôóòåðà çàâåðøåíà 'zoom = ActiveSheet.PageSetup.zoom 'ActiveSheet.ResetAllPageBreaks 'ActiveSheet.PageSetup.zoom = zoom 'iRow2 = iRow2 + 1 'Cells(iRow2, ITOGO_COL) = "Âñåãî ïðèõîä:" 'With Range(Cells(iRow2, FIRST_COL), Cells(iRow2, LAST_COL)) ' .FormulaR1C1 = "=SUBTOTAL(9,R[" & FIRST_ROW - iRow2 & "]C:R[-1]C)" ' .NumberFormat = "0.00" 'End With ActiveWindow.View = viewState '---------------------------------------------------------> '------------------------------------------------------------< 'Âñåãî ïðèõîä: End Sub Sub del_pic() ActiveSheet.Shapes.Range(Array("Ðèñóíîê 1")).Select Selection.Delete End Sub Sub text_del() Cells(1, 1).Select Selection.Clear End Sub 'Sub setHeader() 'Cells(1, 1).Value = "Óâåäîìëåíèå! Äåíåæíîå òðåáîâàíèå ïî îïëàòå íèæåóêàçàííûõ ïîñòàâëåííûõ òîâàðîâ óñòóïëåíî Ïîñòàâùèêîì ÏÀÎ «Ïðîìñâÿçüáàíê» (ÎÃÐÍ 1027739019142) íà îñíîâàíèè Ãåíåðàëüíîãî äîãîâîðà îá îáùèõ óñëîâèÿõ ôàêòîðèíãîâîãî îáñëóæèâàíèÿ ïîñòàâîê âíóòðè Ðîññèè îò" + Chr(34) + "02" + Chr(34) + "ìàðòà 2010ã. ¹ 070-ÂÐ-47-10, â ñâÿçè ñ ýòèì îïëàòó òîâàðîâ íåîáõîäèìî îñóùåñòâëÿòü èñêëþ÷èòåëüíî â ïîëüçó ßðîñëàâëüñêèé ô-ë ÏÀÎ" + Chr(34) + "Ïðîìñâÿçüáàíê" + Chr(34) + "ïî ñëåäóþùèì ðåêâèçèòàì: ÈÍÍ/ÊÏÏ 7744000912 / 760402001, êîð/ñ÷åò 30101810300000000760; ÁÈÊ 047888760, ñ÷åò ¹ 47402810532000846601" 'End Sub |
Я пытаюсь вставить разрыв страницы в конкретный абзац, но он всегда вставляет разрыв страницы в первую строку / абзац документа, я не понимаю почему. Любые идеи?
With Word.ActiveDocument
.Paragraphs(15).Range.Collapse Direction:=wdCollapseEnd
.Paragraphs(15).Range.InsertBreak WdBreakType.wdPageBreak
'or this way (Is there a differece): .Paragraphs(15).Range.InsertBreak Type:=wdPageBreak
End With
Спасибо Юлиус
1 ответ
Лучший ответ
Я вижу другое: для меня он заменяет указанный абзац разрывом страницы, как описано в разделе справки.
В любом случае ключ к этому — работа с конкретным объектом Range
. «Свернуть» весь 15 абзац невозможно — метод не имеет действия. Абзац Range
необходимо назначить независимому объекту Range
, который можно свернуть, а затем вставить разрыв страницы в этот объект Range
.
Например:
Sub TestInsertPageBreak()
Dim paraRange As Word.Range
With ActiveDocument
Set paraRange = .Paragraphs(15).Range
paraRange.Collapse Direction:=wdCollapseEnd
paraRange.InsertBreak WdBreakType.wdPageBreak
End With
End Sub
1
Cindy Meister
26 Янв 2020 в 20:07