Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find and Replace using Word VBA

Status
Not open for further replies.

W1ordvba

Technical User
Dec 12, 2011
7
GB

Hi, I'm trying to look for s apecific word in a document in this case,

l.

And change all occurrences to

lecture.

However, if I use the macro below, it will change words like

roll. to rolLecture which is not what I want.

I only want to see words like

l.

and change them to Lecture.

Hope this makes sense. I have tried to sort this but to no avail. Thx in advance.


Sub ChangeWords_lat()
'
'
'
'

'WANT TO FIND WHOLE WORDS AND NOT PARTS OF WORDS AND REPLACE ONLY

Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

MyString = "l.*"
StringLength = Len(MyString)

If StringLength = 2 Then

With Selection.Find
.Text = MyString
.Replacement.Text = "Lecture"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True 'False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

' only works if alphabet letters are used
'- so command below can't be used on punctuation
' .MatchAllWordForms = True
End With



Selection.Find.Execute Replace:=wdReplaceAll

End If

End Sub
 
Try this code in place of yours:
Code:
Sub ChangeWords_lat()

    Selection.HomeKey Unit:=wdStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    
    MyString = "<l.*"
    StringLength = Len(MyString)
        
    With Selection.Find
        .Text = MyString
        .Replacement.Text = "Lecture"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = True 'False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    
    Selection.Find.Execute Replace:=wdReplaceAll
    
End Sub
 
You can also delete the line:
Code:
StringLength = Len(MyString)
as it doesn't do anything now.
 
I'd suggest:
Code:
Sub ChangeWords_lat()
With ActiveDocument.Range.Find
  .ClearFormatting
  .Text = "<l.>"
  .Replacement.ClearFormatting
  .Replacement.Text = "Lecture"
  .Forward = True
  .Wrap = wdFindContinue
  .Format = False
  .MatchCase = True
  .MatchWholeWord = True
  .MatchWildcards = True
  .MatchSoundsLike = False
  .MatchAllWordForms = False
  .Execute Replace:=wdReplaceAll
End With
End Sub
Note that it probably doesn't matter whether you set MatchWholeWord to True or False

Cheers
Paul Edstein
[MS MVP - Word]
 
Thank you for all your help. Helped so much and just what I needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top