?
Solved

Macro (Find & Replace) for MS Word

Posted on 2016-09-21
10
Medium Priority
?
30 Views
Last Modified: 2016-11-07
I’ve created a Macro (below) for MS Word that finds / replaces (with highlights) key “red flag” terms in contractual documents. It cross-references a master “checklist” (checklist.doc) against the open document and highlights key terms that may need additional review by the appropriate SME.

However, the “MatchWholeWord” function isn’t correctly working with the “checklist” document. For example:
•      The word “lease” is being found in words such as “please” or “release” with only the “lease” portion of the word being highlighted.
•      The word “SLA” is being found in words such as “legislate” with only the “sla” porting being highlighted.
•      The word “govern” is being found in words such as such as “government” with only the “govern” portion of the word being highlighted.

I’m somewhat knowledgeable about macros but it’s been at least 10 years since I was proficient.

Any idea what might be causing the problem?

Thank you for any guidance!

---------------------------------

Sub RedFlags()
    Dim sCheckDoc As String
    Dim docRef As Document
    Dim docCurrent As Document
    Dim wrdRef As String
    Dim wrdPara As Paragraph

    sCheckDoc = "c:\checklist.doc"
    Set docCurrent = Selection.Document
    Set docRef = Documents.Open(sCheckDoc)
    docCurrent.Activate

    Options.DefaultHighlightColorIndex = wdRed
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Highlight = True

    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = True
        .Replacement.Text = "^&"
        .Forward = True
        .Format = True
        .MatchWholeWord = True
        .MatchCase = False
        .MatchWildcards = False
    End With

    For Each wrdPara In docRef.Paragraphs
    wrdRef = wrdPara.Range.Text
        If Asc(Left(wrdRef, 1)) > 32 Then
        ' remove the paragraph mark:
        wrdRef = Left(wrdRef, Len(wrdRef) - 1)

            With Selection.Find
                .Wrap = wdFindContinue
                .Text = wrdRef
                .Execute Replace:=wdReplaceAll
            End With
        End If
    Next wrdPara

docRef.Close
docCurrent.Activate
End Sub

Open in new window


Edit by GrahamSkan: Code put into a code snippet box.
0
Comment
Question by:Cole Bloodworth
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
10 Comments
 
LVL 31

Accepted Solution

by:
Helen Feddema earned 1000 total points
ID: 41809300
I see one problem -- looking for Asc(Left(wrdRef, 1)) > 32 will get you any letter of the alphabet (and lots of other stuff), not just a paragraph mark.  Asc 10 and 13 are the carriage return and linefeed characters, which I think would be the Word paragraph mark.  If you are aiming at getting just alphanumeric text for searching, try this function, which strips out any nonalphanumeric characters (you can modify the list of bad characters as needed -- you may want to retain some of them):

Public Function StripNonAlphaNumericChars(strText As String, _
   blnReplace As Boolean) As String
'Strips a variety of non-alphanumeric characters from a text string,
'with the option of replacing them with spaces
'Created by Helen Feddema 10-15-97
'Modified by Ruud H.G. van Tol 6-18-99
'Modified by Brad Beacham 6-Feb-2005
'Last modified by Helen Feddema 11-May-2016

On Error GoTo ErrorHandler

   Dim strTestString As String
   Dim strBadChar As String
   Dim i As Integer
   Dim strStripChars As String

   strStripChars = " `~!@#$%^&*()-_=+[{]};:',<.>/?" & Chr$(34) _
      & Chr$(13) & Chr$(10)
   strTestString = strText

   For i = 1 To Len(strStripChars)
      strBadChar = Mid(strStripChars, i, 1)
      
      If blnReplace = False Then
         strTestString = Replace(strTestString, strBadChar, vbNullString)
      Else
         strTestString = Replace(strTestString, strBadChar, Chr(32))
      End If
   Next

   StripNonAlphaNumericChars = strTestString
   
ErrorHandlerExit:
   Exit Function

ErrorHandler:
   MsgBox "Error No: " & Err.Number _
      & " in StripNonAlphaNumericChars procedure; " _
      & "Description: " & Err.Description
   Resume ErrorHandlerExit

End Function

Open in new window

0
 
LVL 76

Assisted Solution

by:GrahamSkan
GrahamSkan earned 1000 total points
ID: 41809478
It isn't clear to me what is being searched for in the Selection.Find.

In macros, I always avoid the use of the Selection object, but to use a Range object instead. When you use a range object for the .Find, a new Find object is created, so there is no carry-over from a precious use. With the Selection.Find, settings are from the last time it was used in the current Word instance, so the .Text setting, which is not explicitly set in your code could still have a valid setting.
1
 
LVL 31

Expert Comment

by:Helen Feddema
ID: 41809481
For debugging, it could be helpful to use the Debug.Print statement to show the search term.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 31

Expert Comment

by:Helen Feddema
ID: 41809485
First save it to a variable, then
Debug.Print strSearch
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 41809493
Sorry, I was referring to the first Selection.Find.

It is hard to consider the second part, because it isn't clear what the range of the Selection object now is.
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 41809499
Helen,
I think the questioner is trying to discount empty paragraphs with that construct, but I could be wrong.
0
 
LVL 31

Expert Comment

by:Helen Feddema
ID: 41809512
I think the intention was to strip out the paragraph mark from the word or phrase used for searching -- but in fact the last character of the string is removed.  I think the source doc would work better if it was a table, with each search word or phrase in its own cell, so no paragraph marks would be there in the first place.  Then just select the cell contents and save to a variable for use in searching.
1
 

Author Comment

by:Cole Bloodworth
ID: 41809852
Helen - Thank you for the feedback on the paragraph mark and about using tables as an alternative approach to removing paragraph marks.
0
 

Author Comment

by:Cole Bloodworth
ID: 41809853
Graham - Thank you for the feedback about using a Range object. I'll certainly give it a try.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
Ever visit a website where you spotted a really cool looking Font, yet couldn't figure out which font family it belonged to, or how to get a copy of it for your own use? This article explains the process of doing exactly that, as well as showing how…
This Micro Tutorial well show you how to find and replace special characters in Microsoft Word. This is similar to carriage returns to convert columns of values from Microsoft Excel into comma separated lists.
Office 365 is currently available in five editions. Three of them are for business use: Office 365 Business Essentials, Office 365 Business, and Office 365 Business Premium. Two of them are for home/personal use: Office 365 Home and Office 365 Perso…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question