简体   繁体   中英

VBA Word - iterate through paragraphs to set style

I have a simple script that goes through and sets the style for all paragraphs beginning with a certain character. Easy, I thought. It changes all the paragraphs so they have the same properties as the "Details" Style. But for some reason only the last paragraph ends up with "Details" as its style and all the ones before go back to "Normal". Here's my code so far:

Sub Format_doc()
Dim txt As String

For Each par In ActiveDocument.Paragraphs
    txt = par.Range.Text
    If Left(txt, 1) = "/" Then
        par.Style = "Details"
        par.Range.Text = Right(txt, Len(txt) - 1)
    End If
Next
End Sub

I'd like to keep them attached to the style because I toggle the "hidden" font property in another macro. I'll need to toggle this hidden property for these paragraphs on-and-off several times and assigning a single paragraph style seemed like an easy solution. Here's the other code:

Sub Toggle_hidden()
    ActiveDocument.Styles("Details").Font.Hidden = Not ActiveDocument.Styles("Details").Font.Hidden
End Sub

Solutions? I'm working on Mac, but ultimately this will end up on a Windows.

Your code works fine, here. But perhaps that's due to the version of MacWord... I tested with Office 2016 (Office 365 subscription).

If it's not working for you it may have something to do with the way you're removing the / by basically replacing the paragraph's content. This will also affect the paragraph mark, which is responsible for the paragraph formatting, including the style. Try the following, which explicitly removes the first character and leaves everything else intact:

Sub Format_doc()
Dim txt As String
Dim par As Word.Paragraph

For Each par In ActiveDocument.Paragraphs
    txt = par.Range.Text
    If Left(txt, 1) = "/" Then
        par.Style = "Details"
        'par.Range.Text = Right(txt, Len(txt) - 1)
        par.Range.Characters(1).Delete
    End If
Next
End Sub

Here's a different approach that should also work - and be somewhat faster.

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "^p/"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = False
    .Execute
  End With
  Do While .Find.Found
    With .Duplicate
      .Start = .Start + 1
      .End = .Paragraphs(1).Style = "Details"
    End With
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM