Reputation: 19
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.
Upvotes: 2
Views: 2233
Reputation: 13515
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
Upvotes: 0
Reputation: 25693
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
Upvotes: 1