[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Macro (Find & Replace) for MS Word

Posted on 2016-09-21
10
Medium Priority
?
32 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
Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

 
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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying 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

Using Word 2013, I was experiencing some incredible lag when typing.  Here's what worked for me....
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.
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

650 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