Find/Replace: Find numbers and replace with n-1

A

Alex Wenzel

Hi,

this is not strictly a VBA question (rather about the advanced find/
replace feature), but close:

I'm trying to find out how to find certain numbers inside specific
text strings, modify the text string and replace each number with n-1
(i.e. make >abc=1< to #xyz=0#, >abc=2< to #xyz=1# etc.).
I know how to modify the text string while *preserving* the numbers,
but have no idea how to calculate the n-1 number in the replacement
string.

So I would search for something like \>abc\=([0-9]{1,})\<
and replace it with .... what?

Is there a way to do this w/ find/replace or do I need a full VBA
macro?

Any ideas?
TIA
 
P

periodic

I don't you can do that with a pure find replace. The problem is that regular
expressions are too limited for operations like that. They deal with strings
and replacing strings, they can not modify what they find in that sens. You
have to use some VBA to fix this. Try recording a find replace in a macro and
go from that.

Of course you can do several search and replace and take each number by
itself.
 
H

Helmut Weber

Hi Alex Wenzel,
I'm trying to find out how to find certain numbers inside specific
text strings, modify the text string and replace each number with n-1
(i.e. make >abc=1< to #xyz=0#, >abc=2< to #xyz=1# etc.).
Is there a way to do this w/ find/replace I don't think so.
or do I need a full VBA macro?

Very probably.
Any ideas?

Yes, have a close look at this one:

Sub Test6009()
Dim rDcmn As Range ' range document
Dim sTmp1 As String ' temporary string 1
Dim sTmp2 As String ' temporary string 2
Dim lPstn As Long ' position in a string
Set rDcmn = ActiveDocument.Range
With rDcmn.Find
.Text = "\>abc\=([0-9]{1,})\<"
.MatchWildcards = True
While .Execute
sTmp2 = ""
' rDcmn.Select
sTmp1 = rDcmn.Text
sTmp1 = "#" & Right(sTmp1, Len(sTmp1) - 1)
lPstn = InStr(sTmp1, "=") + 1
While IsNumeric(Mid(sTmp1, lPstn, 1))
sTmp2 = sTmp2 & Mid(sTmp1, lPstn, 1)
lPstn = lPstn + 1
Wend
sTmp2 = CStr(CLng(sTmp2))
lPstn = InStr(sTmp1, "=")
sTmp1 = Left(sTmp1, lPstn) & sTmp2 & "#"
' msgbox sTmp1
rDcmn.Text = sTmp1
rDcmn.Start = rDcmn.End
rDcmn.End = ActiveDocument.Range.End
Wend
End With
End Sub

Improvably in many ways.

HTH

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 
A

Alex Wenzel

Thanks, Helmut.

I missed your reply because I had to get it done quickly and had
already done it manually.
Will try it next time the problem arises.

Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top