PDA

View Full Version : how to find/replace with addition



jnorman
07-15-2007, 03:53 PM
Hi all,

I'm trying to find a way to find several numbers within a word doc, add 1 to that number, and replace the total. I'm having a problem because the numbers are not in a designated field.

For instance, within a table cell, there is much text, one or more instances of text including "#1, #4, etc." Each instance of #x, needs to be replaced with #x+1 on a daily basis. I've tried writing some code, shown below:



Sub Test190()
Dim oRng As Range
Dim sRpl As String
Dim bFnd As Boolean
Dim iNum As Integer
Set oRng = ActiveDocument.Range
sRpl = "#"
With oRng.Find
.Text = "(#)([0-9]{1,})"
With .Replacement
.Text = sRpl & (iNum + 1)
.Font.Name = "Arial"
.Font.Size = 7.5
End With
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
If Not .Found Then
MsgBox "Searchtext not found"
End If
End With
End Sub


This code has the variable iNum, which, in this instance is not defined. I'm having a problem getting the text found into an integer form that can be manipulated.

I'm a newbie at vba, so any help is appreciated.

fumei
07-16-2007, 09:43 AM
Here you go. File attached. Code can be executed by clicking "Test192" on the top toolbar.
Sub Test192()
Dim oRng As Range
Dim sRpl As String
Dim bFnd As Boolean
Dim mySearch As String
Set oRng = ActiveDocument.Range
sRpl = "#"
mySearch = "(#)([0-9]{1,})"
With oRng.Find
.MatchWildcards = True
Do While (.Execute(findtext:=mySearch) = True) = True
oRng.Text = sRpl & Right(oRng.Text, _
Len(oRng.Text) - 1) + 1
bFnd = True
Loop
End With
If bFnd <> True Then MsgBox "Searchtext not found"
End SubWhen using a Range find, what actually happens is that the Range object becomes (temporarily) the range found by .Execute. It is dynamic.

Therefore for each .Execute that is True, oRng becomes the found string. Therefore oRng.Text IS (temporarily) #1, #3, #17....whatever. Therefore...it can be changed.

So....strip off everything after the "#":Right(oRng.Text, Len(oRng.Text) - 1)Add 1 to that, and then make the (current) Range text = "#" & previous number + 1:oRng.Text = sRpl & Right(oRng.Text, Len(oRng.Text) - 1) + 1I am not sure what you mean by "replace the total", as you do not mention how that "total" is achieved.

mdmackillop
07-16-2007, 10:33 AM
The Split function is a little tidier.:beerchug:
oRng.Text = sRpl & Split(oRng.Text, "#")(1) + 1