Consulting

Results 1 to 3 of 3

Thread: Setting styles on 1st and 2nd lines - improve code

  1. #1
    VBAX Newbie
    Joined
    May 2021
    Location
    UK
    Posts
    4
    Location

    Setting styles on 1st and 2nd lines - improve code

    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

  2. #2
    VBAX Regular
    Joined
    Jul 2020
    Location
    Sun Prairie
    Posts
    35
    Location
    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 on the how and why of doing so.

  3. #3
    VBAX Newbie
    Joined
    May 2021
    Location
    UK
    Posts
    4
    Location
    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/q7xcdp4luy...01-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)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •