Solved

Macro (Find & Replace) for MS Word

Posted on 2016-09-21
10
19 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
  • 4
  • 3
  • 2
10 Comments
 
LVL 31

Accepted Solution

by:
Helen_Feddema earned 250 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 250 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
 
LVL 31

Expert Comment

by:Helen_Feddema
ID: 41809485
First save it to a variable, then
Debug.Print strSearch
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Preface: When I started this series, I used the term CommandBars because that is the Office Object class that it discusses. Unfortunately, when Microsoft introduced Office 2007, they replaced the standard Commandbar menus with "The Ribbon" and rem…
Microsoft Word is a program we have all encountered at some point, but very few of us have dug deep into its full scope of features, let alone customized it to suit our needs. Luckily making the ribbon (aka toolbar, first introduced in Word 2007) wo…
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.
In a previous video Micro Tutorial here at Experts Exchange (http://www.experts-exchange.com/videos/1358/How-to-get-a-free-trial-of-Office-365-with-the-Office-2016-desktop-applications.html), I explained how to get a free, one-month trial of Office …

863 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

Need Help in Real-Time?

Connect with top rated Experts

28 Experts available now in Live!

Get 1:1 Help Now