Home | Tips | Library | Other Authors | Other WP Sites | Writer's Links | Contact | Site Map | Donate

Barry MacDonnell's
Toolbox for WordPerfect

Macros, tips, and templates for Corel® WordPerfect® for Windows®
© Copyright 1996-2024 by Barry MacDonnell. All Rights Reserved.

Page updated Nov 20, 2022

REPLACEM - Replace multiple words in one pass

Download REPLACEM.ZIP (Version 1.23; 01/13/16; 20,808 bytes)

Updated in WordPerfect X7 but should work in other versions (back to at least WP9)

WordPerfect 11 users: See important information about using macros in the first release of WP11 (11.0.0.233) at the top of this page.

Downloading, Documentation, Modifications, and Support 

More macros in the Library...

Related macros:

•  If you just need a macro to quickly apply colored highlighting or text attributes (e.g., bold, italics, or redline) to several different words in a document -

▸ See HiLiteDoc to add colored highlighting to one or more different words/phrases.

▸ See the small macros in the footnotes below.

•  If you need replace, add, or remove a text attribute (e.g., bold) from any words that have them with a differentr text attribute (e.g., italic) or a style, see ReplaceCodes.

  

Purpose

Replacem.wcm is a macro that you can use to find and replace many words or phrases in the current document in one easy operation. With it you can make extensive changes to existing documents with a mouse click.

Why use it? 

WordPerfect's QuickCorrect only works to replace words as you type; it can't find and replace existing words. For that you usually use Edit, Find and Replace. But Find and Replace works with a single word or a phrase at a time, whereas this macro can work with dozens of words or phrases at a time.

Replacem.wcm is useful whenever you need to make more than a few Find-and-Replace passes in a document -- especially if you need to repeat the same operation using the same words on additional documents.

For example, the task of editing a book or lengthy contract to change several items can be greatly simplified by using what amounts to an "inclusion" list of words for the macro to find and replace. (You simply store your replacements is a separate, editable WordPerfect file, making it easy to update the word list as well as keep separate lists for different projects.)

[Screen shot of Replacem.wcm menu]

Tips, alternatives and options

•  Note that the macro's menu contains an option to add redline to the replacement words. This might be useful so you can (A) easily view all replacements to verify them, and/or (B) change the Redline later to some other text attribute (e.g., Italics) or even to a style (e.g., one that includes a font change).

You can also add redline (or any text attribute) to the same word or phrase in the document manually, with Edit, Find and Replace. See the next section.

Changing such text attributes later can be done very efficiently with the Replace Codes macro (◄ see left column).

•  WordPerfect X6 (released in 2012) shipped with a new macro, Multiple Find and Replace.wcm, that has a similar purpose to Replacem.wcm.

However, unlike Replacem.wcm it does not allow prompting the user for confirmation, and it does not store the find/replace items for future use. But for the current session with simple words/phrases, it can be easier to use since no separate user document containing replacements is required.

•  If you want to use a macro to either -

(A) quickly apply text attributes (e.g., italics or redline) to several different words in a document, or

(B) replace several different words with other words without creating a separate user document (as is required with Replacem.wcm)

- see the macro snippets in the footnotes below.

Related tips:

▸ If you simply want to add a text attribute such as redline to the same word or phrase in a document, you don't need a macro: you can just use Edit, Find and Replace. [Screen shot of an example. See the footnote on the "How to efficiently use Find..." here for more on how to do it (and even quickly remove the attribute applied to those words the same way).]

▸ If you need to search for a text string and replace it with a similar string, be aware that the replacement might already exist in the document and also contain ("nest") the search string!
    For example, if the search string is "Certificate of Trust" and the replacement is "Amended Certificate of Trust" (here, the latter contains the former string), you could end up with some items containing redundancies: e.g., "Amended Amended Certificate of Trust." (Italics added.)
    Note that this issue can surface with any manual or macro search and replace operation where such similar items are involved.
    One easy solution is to use an intermediary step i
n the search and replace operation using a separate "placeholder" string to "park" the replacement string (if it already exists) out of the way temporarily. See the footnote on the Find and Replace tips page here (both a manual F&R method and a macro method are demonstrated there).

• Also see these macros:

Replace Codes.wcm can replace, add to, or remove a text attribute such as bold, italics, redline, highlighting, etc. from any words that have them. Moreover, when replacing, or adding to, an attribute you can optionally use an existing style instead of a different text attribute. (See next option below.)

HiLiteDoc.wcm adds colored highlighting to one or more words wherever they are found -- good for marking up initial drafts.

•  As noted, you can use styles to change or update various text in a document.

Styles are easy to create and modify. Their purpose is to contain format codes, graphical items, tables, watermarks, margin settings, and even other ("nested") styles. The "container" is then applied wherever desired, instantly changing formatting at that point. They can also be easily and quickly modified, thereby changing all instances of the same style in the document.
 
Instructions and operation

[These instructions also exist at the top of the macro's code.]

Step 1. You must create and save at least one ordinary, separate WordPerfect document (.WPD) containing a list of your items and their replacements. The words must be in a 2-column table in plain text (no formatting codes), as explained below.

This separate document will be "called" by the macro to make the replacements to the specified items in the main document.

This is easy to do with Table, Create (or Format, Table, Create in earlier versions of Wordperfect).

Be sure the separate document contains only a 2-column table, with the first column containing the word or words to replace, and the second column containing the replacement word or words -- each pair in the same row -- something like this:
Replacem.wpd table example

When creating the list -

•  Use plain text. Don't use any formatting (fonts, font sizes, bold, italics, etc.) for the items in the table. Due to the way the macro stores these items, format codes are stripped out.

•  Don't paste. It is better to type the items into the list rather than paste them as unformatted text with Edit, Paste Special since doing this (as of WordPerfect 11; see here) converts normal hyphens (which are codes) into hyphen characters ("hard hyphens"). This means the normal-hyphen item in the document will not be found. Instead, just press the hyphen key if that is the way it was entered in the main document. [Tip: If you are not sure about the type of hyphen in the document at the item's location you can simply add both versions of the hyphenated item to the table list (each in their own table row). For more on the types of hyphens used in WordPerfect see here.]

•  Don't add anything around the table. The only thing in the document should be the 2-column table.

•  Keep the items in Column 1 short. The word or phrase in Row 1, Column 1 is limited by WordPerfect's Find function to about 79 characters (including spaces), so keep all items under this length. Each item in Column 1 will be replaced by the word or phrase in the same table row (in Column 2).

Notes relating to the list -

•  How the macro handles empty cells in the table

During playback, if the macro runs into an empty cell in Column 1, it will terminate immediately, so you don't need to worry about empty rows below your list of replacement words.

However, don't leave empty cells in Column 1 in the middle of your list, or all words following that location won't get replaced!

On the other hand ... an empty cell in Column 2 means the adjacent word or phrase in Column 1 will be replaced with "nothing" (which may still leave behind an extra space). This is the equivalent of manually using WordPerfect's Find and Replace function with <Nothing> entered in the Replace field: It deletes the searched word when it is found.

•  Capitalization and items in lower case

Replacement words (Column 2) are always NOT case-sensitive during macro play, so the replacement will be in the same case of the word(s) you typed in Column 2.

Thus, the replacement item should be capitalized the way you intend it to appear in the document.

Searched words (Column 1) can optionally be case-sensitve. Normally this option is disabled (Off), so if you search for "Word" it will look for both "word" and "Word".

However, you should consider putting all words to be searched case-sensitive -- i.e., Capitalized or in UPPER case (proper names, acronyms, etc.) -- into Column 1 of a different replacement document from the one(s) used for strictly lower case words, and play the macro using that replacement document with the "case sensitive" option enabled. The macro should then find just those capitalized/uppercase words and replace them with the adjacent words in Column 2 of that replacement document.

•  Spaces, periods (full stops), and hard returns?

Don't forget to include spaces or periods where needed in the table cells, especially following any replacement sentences (i.e., Column 2 items) so that they will be inserted in the main document.

For example, the program often "cleans up" extra spaces when you (or a macro) delete some text; an insertion at that point can cause the replacement to "run together" with the following text unless you add a space to the inserted material (i.e., in Column 2).

[Test a few such replacements to see how this works. On the other hand, extra unwanted spaces can be removed later with a macro such as DeSpacer.wcm in the Library.]

Be sure to exclude hard returns in Column 2 of the table unless you really want them. [Extra unwanted hard returns can be removed with a macro such DelExtraHR.wcm in the Library.] 

Step 2. Save the separate document to disk. 

IMPORTANT:

The first replacement list document must be named
REPLACEM.WPD (note the "M" at the end) and be saved in your default macros folder, along with this macro.

[To find the location of your default macro folder: Click Tools, Settings, Files, Merge/Macro and jot down the name. You could save the table document to your regular default folder and then move it to the macro folder with Windows Explorer or equivalent file manager.]

You can create up to 9 additional word list files, naming them (in sequence) REPLACE2.WPD (for the second list) through REPLACE0.WPD (for the last list), to match the macro's menu selections. You could change the names to something more meaningful -- but if you do that, you must also change the macro code in the Menu section of this macro's code to match the new flenames.

Step 3. Play the macro on the current document (always make a backup of the document before you begin).

Tip: If you have set Undo to "on" (with Edit, Undo/Redo History), you can quickly reverse any changes to your current document with Ctrl+Z.

Alternatives

•  Advanced users: If you simply want to use a custom macro to quickly apply text attributes (e.g., italics or redline) to several different words in a document, or replace several items with other items, etc., without creating a separate user document containing search items and their replacements (required with Replacem.wcm), see the macros in the Footnotes area below.

•  If you want to swap individual words or phrases -- for example, "Party 1" and "Party 2" -- wherever they appear in your document, you can use the "A-B-C Word Triangle" method.

What is it? Imagine a triangle with the first word (or list of words) located on one corner (say, the lower left, or corner "A"), the second word (or list of words) on the opposite corner (lthe ower right, or corner "B"), and some sort of intermediate word(s) at the apex (or corner "C"). Like this:

C

A

B

Using this method, you will need to change "A" words to (intermediate) "C" words to "park" them out of the way temporarily. In effect, the "A" words no longer exist for your current purpose in the document. Then you need to change "B" words to "A" words (the first part of the swap). Finally, you need to change the intermediate "C" words to "B" words, completing the swap.

The net result is that you have swapped "A" words ("Party 1") with "B" words ("Party 2").

This can be done with either WordPerfect's Edit, Find and Replace or with the REPLACEM macro (see below.)

Here's how to do it with Edit, Find and Replace, which should be easy enough to use for occasional single A-B word/phrase swaps:

Step 1

First find and replace the first word or phrase (e.g., "Party 1," which is Word A) with an intermediate word (Word C) not used elsewhere in your document.

A "nonsense" word will do nicely, such as ABCD1. This "parks" the word or phrase out of the way temporarily.

[If you are swapping several words or phrases in one session, replace the next word or phrase on your swap list with a different nonsense word such as ABCD2, etc.]

You might want to pause at each item found before replacing it to make sure it's one that should be swapped. (Using Find and Replace, Match, Case can be helpful if there might be confusion with other common words.)

In this step, because you are replacing all "A" words with "C" words you are effectively hiding the "A" words from the next step.

Step 2

After the replacements have been made with nonsense words, replace the second word or phrase with the first. For example, replace "Party 2" with "Party 1".

Again, you might want to pause at each item found before replacing it to make sure it's one that should be swapped.

In this step, you are simply changing all "B" words into "A" words. (There  will no longer be any "B" words in the document.)

Step 3

Finally, find and replace the "C" words (the nonsense words) with the corresponding "B" words.

In this step, you are changing all "C" words into "B" words.

The net result is all "A" and "B" words have been swapped because all instances of "A" words in the document are now "B" words, and all "B" words are now "A" words. (There are no "C" words left since all of them were changed in step 3.)


Using REPLACEM for the task:

For single swaps (i.e., not several find-and-replace items) each of the three steps above can be placed in a separate table row in an external replacement document (described above) that is associated with the REPLACEM macro. [As noted above you could just use Edit, Find and Replace when swapping only a single word/phrase for another word/phrase. However, F&R would require the three separate steps described above.]

If you are using lists of several words/phrases to swap, you might find it easier to use three external replacement documents (described above) for this method. In our example, the first row of the first list would contain the words "Party 1" and "ABCD1." The first row of the second list would contain the words "Party 2" and "Party 1." the first row of the last list would contain the words "ABCD1" and "Party 2." The second and subsequent rows would follow this pattern. You would then play the macro three times using each of the three lists in turn.

•  For a simple macro that swaps any two selected items (e.g., "Party 1" and "Party 2") throughout a document, see SWAPTHEM.



Footnote 1
[Continued from above:]


Purpose

If you only need to apply formatting (bold, italics, Redline, etc.) to several different words or phrases in a document -- wherever they are found -- you can use a macro like EXAMPLE #1 below. (It is based on a macro published by Greg Turner and Kenneth Hobson on WordPerfect Universe here.)

EXAMPLE #1 was designed to help with tasks that typically require adding a format attribute to the same list of various words, such as might be found is a firm's contracts, user manuals, etc.  Hence it employs a list of these words or phrases stored in a separate file on disk.

Tip

Instead of a macro, you can use WordPerfect's Find and Replace feature to apply text formatting (bold, italics, etc.) to a single word or phrase wherever it is found in the document. This is often quicker and easier than using a macro, especially for one-off tasks. See a footnote on the How to efficiently use "Find:" in the Find and Replace (F&R) dialog page here.

Assumption

Suppose you want to apply italics to these particular words that might appear anywhere in a document:
Agreement
Assignment
Leased Premises
Master Lease
Transferor
Transferee

IMPORTANT: If you use different words or phrases you will need to insert them in the separate document as described below.
Instructions

First: To copy the macro code into WordPerfect, see here for instructions on where to store it, save it, etc.

[1]  The simplest thing to do is
first create a separate, plain text (ANSI or ASCII) file with each item on a separate line.

Tips:

This "source words" file can be created with a text editor, or it can be created in WordPerfect and saved as ANSI Text.

For a simpler version of this macro that might appeal to those who write macros "on the fly" see Footnote 2 below.

[2]  Next, modify the macro code below (the items in dark red) to point to the text file on disk and to tell the macro which attribute to apply.

[3]  Play the macro.

Important notes and some tips

•  Keep all words and phrases in the source words file to less than 79 characters per item, including spaces.

This is a limit of the macro language's SearchString() command. While longer items can be written and stored into the macro's Array[] command, only the first 79 characters/spaces of a matching item will be processed (in this example: italicized) in the document.

•  Note that the macro searches for items that match the item's case. Thus, for example, "Agreement" will be processed, but not "agreement."

Tips

If you need both upper- and lower-case versions of a particular word italicized, enter both versions in the Array command (each version on its own line).

On the other hand if you need both upper- and lower-case versions of all words italicized, you can change the SearchCaseSensitive() command's parameter to No! in the ForEach segment.

You can also change the SearchFindWholeWordsOnly() command to process partial words by setting its parameter to No! in the ForEach segment.

•  Other text attributes or relative sizes can be used besides italics; see the variable (vAttr) at the top of the macro's code. Use a number that corresponds to the attribute (e.g., 8=Italics).

•  Once the words are processed, you can instantly delete the attributes, add additional attributes, or change attributes with the REPLACE CODES macro here.

•  Always test the effects of the macro on a copy of your document to see how it works.

EXAMPLE #1
A macro to add an attribute (here, italics) to various words using an external source list of words.
[Be sure to see Instructions, Notes and Tips in paragraphs just above.]

// Macro begins here
// = = = = = = = = = =
// PURPOSE:
// Adds an attribute (here, italics) to all words found in a separate (on disk)
// source list of words (a plain text ANSI or ASCII file) wherever they are
// found in the current document. See Search and Replace settings in
// the ForEach segment, which you can change.

// IMPORTANT:
// The macro searches only for whole words ("Agreement" and not "agree")
// and for case-sensitive items ("Agreement" and not "agreement"). See the
// Search and Replace settings in the ForEach segment, which you can change.

// INSTRUCTIONS:
// (1) Set the drive, path and filename of the external "source list" (text file):

           vFN:="
c:\temp\sourcewords.txt"

// (2) Set the type of attribute to apply in vAttr below -- for example:
//      0=ExtraLarge; 1=VeryLarge; 2=Large; 3=Small; 4=Fine;
//      5=Superscript; 6=Subscript; 7=Outline; 8=Italics; 9=Shadow;
//      10=Redline; 11=DoubleUnderline; 12=Bold; 13=Strikeout;
//      14=Underline; 15=SmallCaps

            vAttr:=
8  // (e.g., 8 = Italics)
// = = = = = = = = = =

// vHRt:=
NToC(0F90Ah)  // (used in messages for a hard return)
// Check if file exists:
FileExists (x; vFN)
If (x=False)
    Messagebox (;"Error - File not found!";vFN+vHRt+"cannot be found.")
    Return
// (exit macro)
Endif

// Call a procedure to set F&R to normal defaults:
pResetFindReplace ()

// This snippet was posted by Kenneth Hobson on WordPerfect Universe at
// http://www.wpuniverse.com/vb/showthread.php?postid=146096#post146096
Array[]=FileToArray(vFN)

// This snippet is modeled after code posted by Greg Turner:
ForEach(vVar;Array[])
    vLen:=StrLen(vVar)
    If(vLen>79)
        Messagebox(;"Caution";
        "The item"+vHRt+vVar+vHRt+
        "is too long and will be skipped.")
        Go(Cont@)
    Endif
    PosDocVeryTop()
    SearchString (vVar)
    ReplaceString (vVar)
     SearchFindWholeWordsOnly (Yes!) // (or use No!)(See Notes above)
     SearchCaseSensitive (Yes!) // (or use No!)(See Notes above)
    ReplaceWithAttributes (Yes!; Attribute: vAttr) // (Yes! is required)
    ReplaceForward (SearchMode: Extended!)
    Label(Cont@)
Endfor

// Return Find and Replace parameters to defaults:
pResetFindReplace () 
Return // (exit macro)

// = = = = = FUNCTIONS AND PROCEDURES HERE = = = = =

// Function by Kenneth Hobson - reads file into array and returns contents:
Function FileToArray(vFile)
hFile=OpenFile (vFile; Read!; Compatibility!; AnsiText!)
If (hFile=OpenFile.Error!)
MessageBox (;"Open File Problem";
    "Error processing password '^0' file!"; IconStop!+HasParameters!; vFile)
    Quit
EndIf
Count=0
While (not FileIsEOF (hFile))
   Count = Count+1
   FileRead (hFile; x)
EndWhile
FilePosition(hFile; 0; FromBeginning!)
Declare TempArray[Count]
x=0
While (not FileIsEOF (hFile))
   x=x+1
   FileRead (hFile; TempArray[x])
EndWhile
CloseFile (hFile)
Return(TempArray[])
EndFunc

Procedure pResetFindReplace ()
SearchString("")  ReplaceString("")
// Only one Match* command can be active at any one time:
// MatchPositionAfter()
// MatchExtendSelection()
// MatchPositionBefore()
MatchSelection()
SearchFindWholeWordsOnly(No!)  MatchWithAttributes(No!)
ReplaceWithAttributes(No!)  SearchCaseSensitive(No!)
ReplaceWithCase(No!)  MatchWithFont(No!)
ReplaceWithFont(No!)  MatchWithFontSize(No!)
ReplaceWithFontSize(No!)  SearchInSelection(No!)
SearchWordForms(No!)  SearchWrap(No!)  MatchLimit(No!)
EndProcedure

// Macro ends here


Footnote 2


Purpose

EXAMPLE #2 below is a simple version (after a macro created by Greg Turner) of the macro in Footnote 1 for those who want to write a code snippet "on the fly" to do a simple job: Add an attribute (e.g., italics) to several different words wherever they are found in a document. (See Tips below for other attributes.)

EXAMPLE #3 below uses a different Search technique (a While...Endwhile loop) so as to apply multiple changes/attributes to the various words it finds.

Instructions

First: To copy the macro code into WordPerfect, see here for instructions on where to store it, save it, etc.

[1]  Enter each word you want to process in your current document on a separate line in the Array[] command below.

With each word/phrase on its own line in the Array[] command, the list can be selected and sorted alphabetically, if desired, to make it easier to maintain and update. [Tip: For a macro that can do the same job as REPLACEM above -- but with a find/replace list created inside the macro code rather than in a separate document -- see Footnote 3.]

[2]  Be sure to replace the sample 6 words in dark red ("Agreement," etc.) inside the Array[] with those words you need to process.

Be sure the last item does not end with a semicolon (see the example in the macro below). If it does, the macro will pop up an error message.

[3] Then play the macro.

Important notes

•  Keep all words and phrases in the source word file to less than 79 characters per item, including spaces.

This is a limit of the macro language's SearchString() command. While longer items can be written and stored into the macro's Array[] command, only the first 79 characters/spaces of a matching item will be processed (in this example: italicized) in the document.

•  Note that the macro searches for items that match the item's case. Thus, "Agreement" will be processed, but not "agreement."

If you need both upper- and lower-case versions of a particular word italicized, enter both versions in the Array command (each version on its own line).

On the other hand if you need both upper- and lower-case versions of all words italicized, you can change the SearchCaseSensitive() command's parameter to No! in the ForEach segment.

You can also change the SearchFindWholeWordsOnly() command to process partial words by setting its parameter to No! in the ForEach segment.

•  There may be a limit to the number of items you can directly assign to an Array[]. It appears to be about 247 items, as noted here.

Tips

☼  Always test the effects of the macro on a copy of your document (or a section of your document) to see how it works.

☼  You can modify the macro (in EXAMPLE #2) to produce other attributes (bold, large, small caps, etc.) Simply replace the parameter, Italics!) in the ReplaceWithAttributes command with any of the following: Bold!, Underline!, DoubleUnderline!, ExtraLarge, VeryLarge!, Large!, Small!, Fine!, SmallCaps!, Redline!, Subscript!, or Superscript!. [However, UPPPER and lower case are not "attributes" (to a computer they are changes in characters) so they require special treatment (see EXAMPLE #3).]

☼  Once the words are processed, you can instantly delete attributes, add additional attributes, or change attributes with the REPLACE CODES macro here.

EXAMPLE #2
A macro to add italics to various items, using a list embedded in the macro.
[Be sure to see Instructions, Notes, and Tips just above.]

Note that Search parameters are reset with a Procedure just before the macro does its work and again before it exits.

Note also the Procedure that will exit substructures (e.g., header, footnote, text box, etc.) when the cursor might be inside one.

// Macro begins here:
// = = = = = = = = = =
// PURPOSE:
// Adds an attribute (in this example, italics) to all words found in a
// list of words embedded in the macro itself (in the Array command),
// wherever they exist in the document.
See Search and Replace
// settings in the ForEach segment, which you can change.

// IMPORTANT:

// The macro searches only for whole words ("Agreement" but not "agree")
// and for case-sensitive items ("Agreement" but not "agreement"). See the
// Search and Replace settings in the ForEach segment, which you can change.
// = = = = = = = = = =

// First, call two procedures:
pResetFindReplace ()
pExitSubstructures ()

// Be sure the last item does NOT end with a semicolon:
Array[]={
"Agreement";
"Assignment";
"Leased Premises";
"Master Lease";
"Transferor";
"Transferee"

}

ForEach (vVar;Array[])
    PosDocVeryTop()
    SearchString (StrgToLookFor: vVar)
    ReplaceString (RplcStrg: vVar)
     SearchCaseSensitive (Yes!) // (or use No!)(See Notes above)
     SearchFindWholeWordsOnly (Yes!) // (or use No!)(See Notes above)
    ReplaceWithAttributes (Yes!; Attribute: Italics!) // (Yes! is required)
    ReplaceForward (SearchMode: Extended!)
Endfor

// Return Find and Replace parameters to defaults:
pResetFindReplace () 
Return // (exit macro)

// = = = = = PROCEDURES HERE = = = = =

Procedure pExitSubstructures ()
// Exit from any header, footer, footnote, endnote,
// text box, graphic caption, etc.:
While (?Substructure)
    vSubDoc:=?CurrentSubDoc
    SubstructureExit 
    If ((vSubDoc=10) or (vSubDoc=11)) BoxEnd (Save!) EndIf
EndWhile
vBoxType:=?BoxContentType
If (vBoxType=1 or vBoxType=3) BoxEnd (Save!) Endif
EndProcedure

Procedure pResetFindReplace ()
SearchString("")  ReplaceString("")
// Only one Match* command can be active at any one time:
// MatchPositionAfter()
// MatchExtendSelection()
// MatchPositionBefore()
MatchSelection()
SearchFindWholeWordsOnly(No!)  MatchWithAttributes(No!)
ReplaceWithAttributes(No!)  SearchCaseSensitive(No!)
ReplaceWithCase(No!)  MatchWithFont(No!)
ReplaceWithFont(No!)  MatchWithFontSize(No!)
ReplaceWithFontSize(No!)  SearchInSelection(No!)
SearchWordForms(No!)  SearchWrap(No!)  MatchLimit(No!)
EndProcedure

// Macro ends here


EXAMPLE #3  
(UPDATED 05/12/19, 09/27/21)
A macro to convert various words to
(1) UPPER case,
(2) Redline, and
(3) Underline using a list of words embedded in the macro.

[Be sure to see Instructions, Notes, and Tips above.]

The main difference between this macro and the previous one is that it does not use the ReplaceWithAttributes() command -- which is limited in that it can be used only once in a given Replace routine.

Instead, the macro uses a
ForEach..EndFor loop containing an internal While..Endwhile loop to search for, and replace, each item individually -- one at a time -- wherever it might be found in the document.

By doing that, it can then apply multiple attributes or other changes to each item (in this example, CAPS first, then Redline, then Underline). The process is typically very quick.

Notes and tips

¤  In EXAMPLE #2 above, each item was added directly into an Array[] command. In this macro, separate variables containing the items (e.g., v01, v02, etc.) are used to "feed" the Array. This makes editing the macro less confusing and MUCH easier to modify for different tasks. [Just be sure to have the same number of named variables (v01...etc) in the Array[] command.]

¤  The variables can be in any order and they can be "empty" (as demonstrated below in the macro code). You can set up dozens of empty variables to make it easy to edit the Array in the future, as long as all "feeder" variable names are included in the Array[] command.

¤  There are two Procedures used in the macro to make it more reliable: It will [1] exit substructures (e.g., header, footnote, text box, etc.) when the cursor might be inside one, and it will [2] reset find and replace search/replace parameters (explained here).

¤  Using a While..Endwhile loop inside a ForEach..Endfor loop allows applying each attribute (e.g., Italics, Bold, Redline, etc.) separately to each item found. That way you can create a macro that can easily apply any attribute -- or several attributes and/or text conversions -- since they are separate, individual commands.

¤  Such loops also give you the opportunity to add code in it to pause and display the matched item to confirm processing it (or the remainder of the items), skipping it, or quitting the macro at the paused location. For a cdoe snippet to create a Yes/No/All/Quit dialog (for use during searches, etc.). See the "vPause=" code inside Replace Codes.wcm here.

// Macro begins here
// = = = = = = = = = =
// PURPOSE:
// Finds (and selects) various text items stored in a list of variables and
// (1) converts those items (for example) to UPPER case, then
// (2) adds Redline to them, then
// (3) adds underline to them.
// These 3 changes can be modified as desired: see the code below.

/*
IMPORTANT:
(1) Unlike in EXAMPLE #2, this macro uses variables to store your item choices.
(2) You can use a different number of variables (12 are used below) as long as each one is also included in the ForEach() command.
In this macro variables (e.g., v01 ... v12) can be in any order and they can be "empty" as demonstrated below. [Use a pair of double quotes ("") to signify "nothing stored" if you don't need all of them.]
(3) Here, the macro searches only for whole words ("Agreement" but not "agree") and for case-sensitive items ("Agreement" but not "agreement"), but you can change this in the commands that follow the SearchNext command.
If using case-sensitive, but you need to find both forms of the item, include both upper and lower case versions in variables for that item.
(See the two Search... commands just prior to the ForEach() loop below.)
*/

// TIPS:
// To replace the items with either lower case items or Initial Caps items:
// Change the ConvertUpperCase command to ConvertLowerCase or
// ConvertCaseInitialCaps.
// [See your WP's Help> Macro Commands for the other commands you can use,
// especially in place of (or in addition to) the lines shown in blue.]
//
// Change the list of characters, word or phrases to convert in the variables
// below (79-character limit for each item) -- one item per variable.
// Items you want to find must be placed between double quotes (all
// variables must have double quotes -- even if unassigned and empty).

v01:="Lorem ipsum"
v02:=""
v03:="Agreement"
v04:="Assignment"
v05:="Leased Premises"
v06:="Master Lease"
v07:="Transferor"
v08:="Transferee"
v09:=""
v10:=""
v11:="Blah, blah, blah"  // (<- note commas: "blah blah blah" is skipped)
v12:=""
// = = = = = = = = = =

// Search for items stored in the variables (v01...v12):
pResetFindReplace ()  // (reset program's search options to the defaults)
OnNotFound(NextOne@)
MatchSelection
SearchFindWholeWordsOnly (Yes!)  // (or use No!)
SearchCaseSensitive (Yes!)  // (or use No!)

// [Be sure the last item does NOT end with a semicolon]
ForEach (vVar; {v01;v02;v03;v04;v05;v06;v07;v08;v09;v10;v11;v12})
    pExitSubstructures ()  // (if inside a substructure, exit from it)
    PosDocVeryTop

    While(True) // (endless loop until not found)
        SearchString (vVar)  // (see items stored in variables above)
        SearchNext (SearchMode: Extended!)

        // The next blue commands can be removed (retain at least one)
        // or changed:
        ConvertCaseUppercase
        AttributeAppearanceToggle (Redline!)
        AttributeAppearanceToggle (Underline!)
        // ...Here are more optional changes you can make to the listed
        // words/phrases assigned to the variables (v01...etc) above, such
        // as a change in position, relative size, and/or to add the current
        // highlight color. NOTE: To enable any of these next blue
        // commands remove their leading "//" marks:
        // AttributePositionToggle (Superscript!)
        // AttributeRelativeSizeToggle (Large!)
          
// HighlightToggle

        SelectMode(Off!)
    Endwhile
    Label(NextOne@)
Endfor

// Exit here:
pResetFindReplace () // (first: restore F&R defaults)
Return


// = = = = = PROCEDURES HERE = = = = =

Procedure pExitSubstructures ()
// Exit from any header, footer, footnote, endnote,
// text box, graphic caption, etc.:
While (?Substructure)
    vSubDoc:=?CurrentSubDoc
    SubstructureExit
    If ((vSubDoc=10) or (vSubDoc=11)) BoxEnd (Save!) EndIf
EndWhile
vBoxType:=?BoxContentType
If (vBoxType=1 or vBoxType=3) BoxEnd (Save!) Endif
EndProcedure

Procedure pResetFindReplace ()
// Set search and replace options using WordPerfect default settings
SearchString("")  ReplaceString("")
// Only one Match* command can be active at any one time:
// MatchPositionAfter()
// MatchExtendSelection()
// MatchPositionBefore()
MatchSelection()
SearchFindWholeWordsOnly(No!)  MatchWithAttributes(No!)
ReplaceWithAttributes(No!)  SearchCaseSensitive(No!)
ReplaceWithCase(No!)  MatchWithFont(No!)
ReplaceWithFont(No!)  MatchWithFontSize(No!)
ReplaceWithFontSize(No!)  SearchInSelection(No!)
SearchWordForms(No!)  SearchWrap(No!)  MatchLimit(No!)
EndProcedure

// Macro ends here


Footnote 3


Purpose

Here is a macro (EXAMPLE #4 below) posted by Roy "lemoto" Lewis on WordPerfect Universe (4/16/08, and modified slightly here) that finds each word/phrase in a list and replaces it with another word/phrase. For example:

...replace "first" with "second"
...replace "his" with "her"
...replace "this" with "that"

Instructions

First: To copy the macro code into WordPerfect, see here for instructions on where to store it, save it, etc.

[1] Enter each pair of words or other items you want to process in your document on a separate line in the Array[] command below. With each pair of items on its own line in the Array[] command, the list can be selected and sorted alphabetically, if desired, to make it easier to maintain and update.

[2] Be sure to replace the sample pairs of items in dark red ({"first; second"}, etc.) inside the Array[] with those items you need to process. Be sure the last item does not end with a semicolon (see the example in the macro below). If it does, the macro will pop up an error message.

[3] Then play the macro.

Important notes and some tips


•  Unlike REPLACEM above, this macro does not use a separate list (external file); rather, it uses a simple 2-dimension array to store the find/replace pairs. Therefore, you need to edit the macro and change the array to list your particular items. In other words, be sure to REPLACE the sample 3 pairs (in dark red) inside the Array[] with those words you need to process. Also be sure the last item does NOT end with a semicolon.

[As a matter of interest to those curious about the third parameter in the ForNext command below (i.e., Array[0]/2 ), this simply takes the number of items (elements) in the array (which is stored in [0]) and divides it by 2 to determine the total number of word pairs to process. The ForNext loop then executes that particular number of times. In the example below, with six items in the array, ForNext executes three times, one time for each pair of items.]

•  Keep all words and phrases in the source word file to less than 79 characters per item, including spaces. (An "item" in this context is an element in the array; here, there are two elements per find/replace operation.) This is a limit of the macro language's SearchString() command. While longer items can be written and stored into the macro's Array[] command, only the first 79 characters/spaces of a matching item will be processed.

•  There may be a limit to the number of items you can directly assign to an Array[]. It appears to be about 247 items, as noted here.

•  The macro processes the document from the current cursor location onward by setting a simple bookmark at that location and returning to it later. You could remove the four existing Bookmark commands and add the command, PosDocVeryTop, at both the beginning of the macro and again just after the ReplaceForward command. [For a sample macro that processes just within a block of pre-selected text, see Footnote 4 below.]

•  As written, the macro will ignore headers, footers, footnotes, endnotes, text boxes, and other "substructures." But these could be selected individually before playing the macro on each of them.

•  Note the three search qualifiers that precede the actual search and replace commands:

SearchCaseSensitive (Yes!)
SearchFindWholeWordsOnly (Yes!)
ReplaceWithCase (Yes!)

[You may want to remove one or more of these to suit your own find/replace requirements. The default values (No!) are set at the top of the code with a Procedure.]

•  Always test the effects of the macro on a copy of your document to see how it works.

•  CAUTION: In some circumstances, replacing one text string such as "Certificate of Trust" with another (longer) string such as "Amended Certificate of Trust" can be problematic if the latter already exists in the document.
    Reason: The longer item contains the shorter one, so a search for the shorter string can cause a replacement of it when found inside any existing versions of the longer one. This can result in awkward redundancies such as "Amended Amended Certificate of Trust". (Italics added here for clarity.) Moreover, the problem becomes worse with successive search operations of this specific type in the same document.
    Solutions: See the macro at the end of this footnote on the Find and Replace page.

Alternate (optional) purpose (updated 8/21/14):

You can use the macro to replace each specified string with the same string preceded by a unique character not used elsewhere in the document (such as the heart symbol (♡)). For example,

...replace "first" with "first"
...replace "his" with "his"
...replace "this" with "this"

This would allow you to (later) search for each item in the order of appearance in the document by simply using Find and Replace (or a macro Search) to locate each symbol, one after the other. (All such symbols can then be deleted at once with Find and Replace.) For an example, see this post on WordPerfect Universe (which also searches for tabs, spaces, and double quotation marks using the NToC() command). [See also the cautionary note above.]

EXAMPLE #4  
[Be sure to see Instructions, Notes and Tips just above.]

// Macro begins here:
// = = = = = = = = = =
// PURPOSE:
// This macro
finds each word/phrase in a list and replaces it with another
// word/phrase.

// IMPORTANT:
// (1) Enter your own find-and-replace pairs below, following the pattern of the
// first 3 items.
Note that each item (element) in a pair should not exceed
// 79 characters (including spaces).
// (2) W
hen finished entering your own list, delete the first 3 "sample" items.
// (3) See also the Search and Replace settings prior to the ForNext segment,
// which you can change.

// TIPS:
// The ReplaceForward(Regular!) command does not replace inside headers,
// footers, watermarks,
footnotes, endnotes, text boxes. To replace in them,
// use ReplaceForward(Extended!).
// = = = = = = = = = =

// Call a procedure to set search options to program defaults:
pResetFindReplace ()

// Define the words and phrases (79-character limit for each item) to process.
// [Be sure the last Array item does NOT end with a semicolon.]
Array[]={
{"first";"second"};
{"his";"her"};
{"this";"that"}
}

Prompt ("Replacing";"Please wait"; NoButtons!| InformationIcon!)
BookmarkCreate ("cursor_location") // (see Notes above)

SearchCaseSensitive (Yes!) // (or use No!)(See Notes above)
SearchFindWholeWordsOnly (Yes!) // (or use No!)(See Notes above)
ReplaceWithCase (Yes!) // (or use No!)(See Notes above)

ForNext(i;1;Array[0]/2) // ([0]/2 = total elements divided by 2)
    PosDocVeryTop
    SearchString (Array[i;1]) // (search for the first element in the pair)
    ReplaceString (Array[i;2]) // (replace with the second element in the pair)
    ReplaceForward (Regular!)
    BookmarkFind ("cursor_location") // (see Notes above)
EndFor

// Return to original cursor location:
BookmarkFind ("cursor_location") // (see Notes above)
BookmarkDelete ("cursor_location") // (see Notes above)

EndPrompt

// Return Find and Replace parameters to defaults:
pResetFindReplace ()
Return // (exit macro)

// = = = = = PROCEDURES HERE = = = = =

Procedure pResetFindReplace ()
SearchString("")  ReplaceString("")
// Only one Match* command can be active at any one time:
// MatchPositionAfter()
// MatchExtendSelection()
// MatchPositionBefore()
MatchSelection()
SearchFindWholeWordsOnly(No!)  MatchWithAttributes(No!)
ReplaceWithAttributes(No!)  SearchCaseSensitive(No!)
ReplaceWithCase(No!)  MatchWithFont(No!)
ReplaceWithFont(No!)  MatchWithFontSize(No!)
ReplaceWithFontSize(No!)  SearchInSelection(No!)
SearchWordForms(No!)  SearchWrap(No!)  MatchLimit(No!)
EndProcedure

// Macro ends here


Footnote 4


Purpose


EXAMPLE #5 below is a variation of EXAMPLE #4 in Footnote 3. However, instead of processing the document from the cursor location onward it processes only within a block of pre-selected text. 

[CAUTION: The macro uses the BookmarkBlock command, which can sometimes move or delete existing bookmarks when it re-selects text that includes such bookmarks. Hence it is a good idea to always use it on a backed up copy of the document. If you don't have bookmarks in the selected text then it should not present a problem.]

Instructions

First: To copy the macro code into WordPerfect, see here for instructions on where to store it, save it, etc.

[1] Enter each pair of words or other items you want to process in your document on a separate line in the Array[] command below. With each pair of items on its own line in the Array[] command, the list can be selected and sorted alphabetically, if desired, to make it easier to maintain and update.

[2] Be sure to replace the sample pairs of items in dark red ({"first; second"}, etc.) inside the Array[] with those items you need to process.  Be sure the last item does not end with a semicolon (see the example in the macro below). If it does, the macro will pop up an error message.

[3] Then play the macro.

Important notes and some tips

•  Unlike REPLACEM above, this macro does not use a separate list (external file); rather, it uses a simple 2-dimension array to store the find/replace pairs. Therefore, you need to edit the macro and change the array to list your particular items. In other words, be sure to REPLACE the sample 3 pairs (in dark red) inside the Array[] with those words you need to process. Also be sure the last item does NOT end with a semicolon.

[As a matter of interest to those curious about the third parameter in the ForNext command below (i.e., Array[0]/2 ), this simply takes the number of items (elements) in the array (which is stored in [0]) and divides it by 2 to determine the total number of word pairs to process. The ForNext loop then executes that particular number of times. In the example below, with six items in the array, ForNext executes three times, one time for each pair of items.]

•  Keep all words and phrases in the source word file to less than 79 characters per item, including spaces. (An "item" in this context is an element in the array; here, there are two elements per find/replace operation.) This is a limit of the macro language's SearchString() command. While longer items can be written and stored into the macro's Array[] command, only the first 79 characters/spaces of a matching item will be processed.

•  There may be a limit to the number of items you can directly assign to an Array[]. It appears to be about 247 items, as noted here.

•  The macro processes all items found in the currently selected text by setting simple paired bookmark commands (shown in blue) to allow the macro to easily re-select the selection with each pass. [For a sample macro that processes from the current cursor location to the end of the document, see Footnote 3 above.] 

•  As written, the macro will ignore headers, footers, footnotes, endnotes, text boxes, and other "substructures." But these could be selected individually before playing the macro on each of them.

•  Finally, note these three search qualifiers that precede the actual search and replace commands:

SearchCaseSensitive (Yes!)
SearchFindWholeWordsOnly (Yes!)
ReplaceWithCase(Yes!)

[You may want to remove one or more of these to suit your own find/replace requirements. The default values (No!) are set at the top of the code with a Procedure.]

•  Always test the effects of the macro on a copy of your document to see how it works.

EXAMPLE #5 
A variation of EXAMPLE #4 that
processes only within a block of pre-selected text
[See Instructions, Notes and Tips just above.]

// Macro begins here:
// = = = = = = = = = =
// PURPOSE:
// This macro is a variation of EXAMPLE #4 in Footnote 3.
// However, instead of processing the document from the cursor location
// onward it processes only within a block of pre-selected text. 

// IMPORTANT:
// (1) Enter your own find-and-replace pairs below, following the pattern of
//
the first 3 items. Note that each item (element) in a pair should not exceed
// 79 characters (including spaces).
// (2) When finished entering your own list, delete the first 3 "sample" items.
// (3) See also the Search and Replace settings prior to the ForNext segment,
// which you can change.

// TIPS:
// The ReplaceForward(Regular!) command does not replace inside headers,
// footers, watermarks,
footnotes, endnotes, text boxes. To replace in them,
// use ReplaceForward(Extended!).

// = = = = = = = = = =

// Call a procedure to reset search parameters to default states:
pResetFindReplace ()

// Create a paired bookmark around selection of text, then re-select it:
BookmarkCreate ("current_selection")
BookmarkBlock ("current_selection")

// Be sure the last item-pair does NOT end with a semicolon:
Array[]={
{"first";"second"};
{"his";"her"};
{"this";"that"}

}

SearchCaseSensitive (Yes!)  // (or use No!)(See Notes above)
SearchFindWholeWordsOnly (Yes!)   // (or use No!)(See Notes above)
ReplaceWithCase (Yes!)   // ((or use No!)(See Notes above)
SearchInSelection (Yes!)  // (required to search only inside selected block)

ForNext(i;1;Array[0]/2)
    PosBlockTop  // (not really neededbut useful with some other ForNext loops)
    SearchString (Array[i;1]) // (search for the first element in the pair)
    ReplaceString (Array[i;2]) // (replace with the second element in the pair)
    ReplaceForward (Regular!)  // (execute the replacements)
    BookmarkBlock ("current_selection") // (re-select the selection)
EndFor

// These next 2 commands to position the curosr and
// remove Select Mode are OPTIONAL:
PosBlockBottom
SelectMode (Off!)


// Clean up: Remove bookmark code:
BookmarkDelete ("current_selection")


// Return Find and Replace parameters to defaults:
pResetFindReplace ()

Return // (exit macro)

// = = = = = PROCEDURES HERE = = = = =

Procedure pResetFindReplace ()
SearchString("")  ReplaceString("")
// Only one Match* command can be active at any one time:
// MatchPositionAfter()
// MatchExtendSelection()
// MatchPositionBefore()
MatchSelection()
SearchFindWholeWordsOnly(No!)  MatchWithAttributes(No!)
ReplaceWithAttributes(No!)  SearchCaseSensitive(No!)
ReplaceWithCase(No!)  MatchWithFont(No!)
ReplaceWithFont(No!)  MatchWithFontSize(No!)
ReplaceWithFontSize(No!)  SearchInSelection(No!)
SearchWordForms(No!)  SearchWrap(No!)  MatchLimit(No!)
EndProcedure

// Macro ends here