Solved

Macro (Find & Replace) for MS Word

Posted on 2016-09-21
10
26 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 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
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

 
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

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.

Question has a verified solution.

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

Suggested Solutions

I would like to show you some basics you can do with Mailings in MS Word. It´s quite handy feature you can use for creating envelopes, labels, personalized letters etc. First question could be what is this feature good for? Mailing can really he…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
This video walks the viewer through the process of creating an MLA formatted document, as well as a bibliography with citations.
This Experts Exchange video Micro Tutorial shows how to tell Microsoft Office that a word is NOT spelled correctly. Microsoft Office has a built-in, main dictionary that is shared by Office apps, including Excel, Outlook, PowerPoint, and Word. When …

730 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