PDA

View Full Version : Setting styles on 1st and 2nd lines - improve code



bremhillbob
05-13-2021, 06:27 AM
Hi all,
I have a 200 page document. The first line of each page needs to be in 'Heading1' style and line 2 in a style called 'Artist'

Currently they might have mixed attributes so I want to clear these first.

I've used 'record Macro' to get to something that works but it is slow and I suspect is clumsy. Whilst it isn't 'vital' because I can always wait 30 seconds for this macro to run but I would like to learn.

I'd welcome either comments or a more efficient version?

Bob
My code is:
Sub SetHeadings()
'
Application.ScreenUpdating = False
MsgBox ("this could take a while")
For x = 1 To 200
Selection.GoToNext wdGoToPage
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Range.Case = wdTitleWord
With Selection
.ClearFormatting
End With
Selection.Style = ActiveDocument.Styles("Heading 1")
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
With Selection
.ClearFormatting
End With
Selection.Style = ActiveDocument.Styles("Artist")
Next
Application.ScreenUpdating = True
MsgBox ("Finished")
End Sub

Chas Kenyon
05-13-2021, 08:36 AM
Does your Heading 1 style include page-break-before formatting or space-before/after? If so, running this will likely change the pagination. You are working with the selection object rather than the range object. This will always be slower.

It would help if you could include a link to a sample document with the problem. Here is my article on the Microsoft site (https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_win10-mso_365hp/why-a-sample-file-is-important-for-troubleshooting/9441ae3c-1e92-41c6-9a1f-5b377b08e5a5?tm=1619027698258) on the how and why of doing so.

bremhillbob
05-13-2021, 10:16 AM
Hi Chas, pretty much the standard Heading 1 style I think - have to admit that I don't fully understand all the 'Modify Style' options. The document is here:
https://www.dropbox.com/s/q7xcdp4luy64ph4/Books%201-5.docm?dl=0

With my script the page layout seems to be OK.

Whilst it is all OK at the moment I will be adding more to it so having a faster script would help.
(NB - I've recently added another 60+pages so altered the For>Next appropriately)