Take the word from the link to the document and use it to search and replace later in the document?

I do not own VBA, but I would like to configure a macro that performs a certain action with Mocrosoft Word 2003 (yes, I am limited to 2003 software of my company - do not ask!).

I have a number of documents regarding individuals. They all begin with a link to a document 15/3/ARTF/(NAME), where (NAME)is the name of the person, for example 15/3/ARTF/JONES.

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

How to configure a macro to retrieve a name in a document link and find and replace ~Name~with that name (in case of a sentence)? In the example shown, I would like the sentence to say: "Jones passed his navigation exam" at the end of the macro.

+4
source share
1 answer

Assuming the link to the document is a separate paragraph (and the first) in the document, you start with this. If it matches the format you specify, you simply find the last occurrence /, take the name after the found index, and do find-replace to replace all the occurrences ~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

, , , . , ; -)

+2

Source: https://habr.com/ru/post/1619847/


All Articles