I have a problem to replace some serial number such as [30] [31] [32]... to [31] [32] [33]... in MS word when I insert a new references in the middle of article. I have not found a solution way in GUI so I try to use VBA to do that replacement. I find a similar problem in stack overflow:
MS Word Macro to increment all numbers in word document
However, this way is a bit inconvenient because it have to generate some replacement array in other place. Can I make that replacement with regex and some function in MS Word VBA like code below?
Sub replaceWithregExp()
Dim regExp As Object
Dim regx, S$, Strnew$
Set regExp = CreateObject("vbscript.regexp")
With regExp
.Pattern = "\[([0-9]{2})\]"
.Global = True
End With
'How to do some calculations with $1?
Selection.Text = regExp.Replace(Selection.Text, "[$1]")
End Sub
But I don't know how to do some calculations with $1 in regExp? I have try use "[$1+1]" but it return [31+1] [32+1] [33+1]. Can anyone help? Thanks!
Here is a simple VBA macro you can use to achieve this :
It is impossible to pass a callback function to the
RegExp.Replace
, so you have the only option: useRegExp.execute
and process matches in a loop.Here is an example code for your case (I took a shortcut since you only have the value to modify inside known delimiters,
[
and]
.)Here,
Selection.Text = Left(Selection.Text, m.FirstIndex+1)
- Get what is before& Replace(m.Value, m.Value, CStr(CInt(m.Submatches(0)) + 10))
- Add10
to the captured number& Mid(Selection.Text, m.FirstIndex + Len(m.Value))
- Append what is after the captureThat should do the trick :
To use this, remember to add the reference :