2013-11-29 3 views
0

Я пытаюсь написать макрос VBA для MS Word 2010, который заглавны буквами после специального символа. В моем случае подчеркивание «_». Слова, которые я хочу пересмотреть, начинаются со специального префикса. У меня возникают проблемы с операцией замены. Я использую Microsoft Regular Expression Library 5.5.MS Word RegEx заглавные буквы после специального символа

Это то, что я до сих пор:

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") 

я из идей, что делать, чтобы получить его за работой. Можете ли вы указать, что такое моя ошибка и как ее исправить?

ответ

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") 
+0

Ах право, это имеет смысл. Но это не похоже на единственную проблему в скрипте. StartIndex не указывает, где я этого ожидал. Если я делаю Debug.Print (ActiveDocument.Range (Start: = startIndex, End: = endIndex) .Text), я не получаю то же самое с Debug.Print (Match.Value). Как это возможно? –

Смежные вопросы