4
votes

I am not proficient with VBA but would like to set up a macro that does a specific action with Mocrosoft Word 2003 (yes, I am limited to 2003 by my company software- don't ask!).

I have a number of documents concerning individuals. They all start with the document reference 15/3/ARTF/(NAME) where (NAME) is the surname of the individual, for example 15/3/ARTF/JONES.

The documents are based on a template I have created that says things like "~Name~ has passed her navigation exam".

How can I set up a macro to extract the name in the document reference and find and replace ~Name~ with that name (in sentence case)? In the example shown, I would like the sentence to say "Jones has passed her navigation exam" on completion of the macro running.

1

1 Answers

2
votes

Assuming the document reference is a separate paragraph (and the first) in the document, you start by taking that. If it follows the format you specified, you simply find the last occurrence of /, take the name after the found index and do a find-replace to replace all occurrences of ~Name~.

Sub ReplaceNames()
    Dim ref As String
    ref = ActiveDocument.Paragraphs(1).Range.Text

    Dim name As String
    name = Mid(ref, InStrRev(ref, "/") + 1)

    'If name ends with a paragraph, remove it.
    If Right(name, 1) = Chr(13) Then name = Left(name, Len(name) - 1)

    ActiveDocument.Range.Find.Execute "~Name~", MatchCase:=False, ReplaceWith:=name, Replace:=wdReplaceAll
End Sub

Note that I have inserted a check to see if the name contains a paragraph. You don't want new paragraphs appearing all over your document ;-)