Solved

Macro (Find & Replace) for MS Word

Posted on 2016-09-21
10
16 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
First save it to a variable, then
Debug.Print strSearch
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Graham - Thank you for the feedback about using a Range object. I'll certainly give it a try.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
Using Word 2013, I was experiencing some incredible lag when typing.  Here's what worked for me....
This video shows where to find the word count, how to display it, and what it breaks down to in Microsoft Word.
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 …

762 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

10 Experts available now in Live!

Get 1:1 Help Now