当我在文章中间插入新的参考文献时,在 MS Word 中将某些序列号(例如 [30] [31] [32]... 替换为 [31] [32] [33]... 时遇到问题。我还没有在 GUI 中找到解决方案,所以我尝试使用 VBA 来进行替换。我在堆栈溢出中发现了类似的问题:
MS Word 宏可增加 Word 文档中的所有数字 https://stackoverflow.com/questions/30154503/ms-word-macro-to-increment-all-numbers-in-word-document
然而,这种方式有点不方便,因为它必须在其他地方生成一些替换数组。我可以用正则表达式和 MS Word VBA 中的某些函数(如下面的代码)进行替换吗?
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
但我不知道如何用 regExp 中的 $1 进行一些计算?我尝试使用“[$1+1]”,但它返回[31+1] [32+1] [33+1]。有人可以帮忙吗?谢谢!
无法将回调函数传递给RegExp.Replace
,所以你有唯一的选择:使用RegExp.execute
并循环处理匹配。
这是您的案例的示例代码(我采取了快捷方式,因为您只有在已知分隔符内修改的值,[
and ]
.)
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?
' Removing regExp.Replace(Selection.Text, "[$1]")
For Each m In regExp.Execute(Selection.Text)
Selection.Text = Left(Selection.Text, m.FirstIndex+1) _
& Replace(m.Value, m.Value, CStr(CInt(m.Submatches(0)) + 10)) _
& Mid(Selection.Text, m.FirstIndex + Len(m.Value))
Next m
End Sub
Here,
-
Selection.Text = Left(Selection.Text, m.FirstIndex+1)
- 获取之前的内容
-
& Replace(m.Value, m.Value, CStr(CInt(m.Submatches(0)) + 10))
- Add 10
到捕获的号码
-
& Mid(Selection.Text, m.FirstIndex + Len(m.Value))
- 附加捕获后的内容
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)