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 John Tel 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 VBA Word Macro Problem 1

Status
Not open for further replies.

jhernon

MIS
Sep 9, 2006
3
US
I have code (as a macro) that I want to locate all instances of oNum in a Word document and then replace it with ascending numbers starting with 1. I am doing document assembly where there can be a varying amount of oNum in each document. I've tried working with If, Then and For, Next, but don't have a firm grasp of VBA yet. This code will replace all oNum with 1, but I can't get the sequential numbering to work. Here's the code:

Sub Find_Count()
'
' Find_Count Macro
' Macro recorded 9/9/2006

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "oNum"
.Replacement.Text = "1"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
 
Use wdReplaceOne instead of wdReplaceAll, use an incremented variable instead of "1" as replacement text and do the replacement inside a loop.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Thanks, PH. I'm still not getting it, none of my looping compiles. I also don't know how to tell it to stop when it has found the last one (oNum). I'm a systems guy, and not a programming wizard yet. Any more insight?
 
I see NO loop attempt in your posted code ...
 
There are a few other ways to do this, but one way would be:
Code:
Sub IncrementoNum1()
Dim i As Integer
i = 1
Selection.HomeKey Unit:=wdStory
With Selection.Find
   .ClearFormatting
   Do While (.Execute(findtext:="oNum", Forward:=True) = True) = True
      Selection.Delete
      Selection.TypeText Text:=i & " "
      i = i + 1
   Loop
End With
End Sub
This is assuming thet oNum is in fact text. As PH mentions, you need to do the replacement within a loop, with an incrementing variable.

Gerry
My paintings and sculpture
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top