0
votes

I am trying to create a Word macro that will go through a large document that I have and add the text "SAMPLE" to the beginning of every paragraph. The document contains a Title page, Table of Contents and Headings throughout and I would prefer none of these have the "SAMPLE" text on them, just the paragraphs.

Below is some macro code I have found on various sites and kind of pieced together to do somewhat of what I want. It does place the "SAMPLE" text at the beginning of some paragraphs but not all, usually only the first paragraph of a new section within my document. And it also places it at the end of the Table of Contents and Beginning of the Title page. I am brand new to macros in Word so any help is appreciated or if there is a better way of doing this perhaps? There might even be some unnecessary bits in this code since it is pieced together from other samples.

Sub SAMPLE()

Application.ScreenUpdating = False
Dim Par As Paragraph, Rng As Range
For Each Par In ActiveDocument.Paragraphs

  If Par.Style = "Normal" Then
    If Rng Is Nothing Then
      Set Rng = Par.Range
    Else
      Rng.End = Par.Range.End
    End If
  Else
    Call RngFmt(Rng)
  End If

  If Par.Range.End = ActiveDocument.Range.End Then
    Call RngFmt(Rng)
  End If

Next
Application.ScreenUpdating = True
End Sub

Sub RngFmt(Rng As Range)
If Not Rng Is Nothing Then
  With Rng
    .End = .End - 1
    .InsertBefore "SAMPLE"

  End With
  Set Rng = Nothing
End If
End Sub
1
Before Writing any code you should check your document to see what styles are used. If normal paragraphs have a distinctive style then this is a trivial task. Otherwise you need to defined some rules to define paragraphs that you don't want the extra text to appear before.freeflow
All of my paragraphs use the Style normal, which is why I am unsure why the SAMPLE text is only appearing at the beginning of some of the paragraphs. If all the paragraphs are Normal shouldn't this condition be applied to all of them? Not just the first one at the beginning of a new section?TunaBooties
@TunaBooties So how did you get your Title page, Table of Contents and Headings etc. all to use the Normal Style?macropod
Have you checked that your “paragraphs” ARE actually paragraphs? Turn on “Show formatting marks” and make sure the paragraphs end with a paragraph mark rather than a manual line break.Timothy Rylatt

1 Answers

0
votes

Provided your Title, Table of Contents and Headings etc. don't use the Normal Style - as they shouldn't - you really don't need a macro for this - all you need is a wildcard Find/Replace where:

Find = [!^13]*^13
Replace = SAMPLE: ^&

and you specify the Normal Style as a Find formatting parameter. You could, of course, record the above as a macro, but that seems overkill unless you're doing this often.