我正在尝试为MS Word 2010编写VBA宏,以便在特殊字符后大写字母。在我的情况下,下划线“_”。我要修改的单词,以特殊前缀开头。我在更换操作时遇到问题。我正在使用Microsoft正则表达式库5.5。
这是我到目前为止所做的:
Sub ReplaceFunc()
'
' ReplaceFunc Macro
'
'
Debug.Print ("entered replaceFunc")
Dim myRegex As New RegExp
myRegex.Global = True
myRegex.IgnoreCase = False
myRegex.MultiLine = True
' i want to find all words in the document which start with BlaBlub and have a suffix like _foo_bar or _foo_bar_foo
' e.g. BlaBlub_foo_bar, BlaBlub_foo_foo_bar_bar, BlaBlub_foo_bar_foo
myRegex.Pattern = "\bBlaBlub(_([a-z])+)+\b"
' works i get the results i was looking for
Set Matches = myRegex.Execute(ActiveDocument.Range.Text)
' now i want to capitalize every letter after a "_", e.g. BlaBlub_foo_bar --> BlaBlub_Foo_Bar
For Each Match In Matches
' The idea is to run a new RegEx on every found substring but this time with replace
Dim mySubRegex As New RegExp
mySubRegex.Global = True
mySubRegex.IgnoreCase = False
mySubRegex.MultiLine = True
' Matching every underscore followed by a non capital letter
mySubRegex.Pattern = "_([a-z])"
' getting start and endindex from the match to run the regex only on the found word
startIndex = Match.FirstIndex
endIndex = (Match.FirstIndex + Match.Length)
' where it fails with a syntax error
mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")
Next
Debug.Print ("leaving replaceFunc")
End Sub
VBA宏因行中的语法错误而失败:
mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")
我没有想法,该怎么做才能让它发挥作用。你能指出我的错误是什么以及如何解决它吗?
答案 0 :(得分:1)
这很容易纠正,只是抑制括号:
mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")
=>
mySubRegex.Replace ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1"
或者
Dim varVal
varVal = mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")