Search code examples
vbams-wordword-2010

Edit and wrap search result in parenthesis


I want to find all occurences of the string "no." + 1-2 integers between 1 and 9. Then to delete the "no." and wrap the integer/s between paranthesis: "(4)" or "(67)". E.g. "no. 34" should become "(34)".

I seem to have multiple issues (Word 2010):

  1. The code only substitutes one integer. How do I make it find both one or two integers?
  2. How do I make the .Replacement.Text contain the numbers but not the word "no." (I've just put in XXXXX this far).
  3. My code does add paranthesis, but at the beginning and end of the active document. How do I make it wrap the numbers instead?

    With Selection.Find  
        .Text = "n[or]. [1-9]"  
        .Replacement.Text = "XXXXX"  
        .Forward = True  
        .Wrap = wdFindContinue  
        .Format = False  
        .MatchCase = False  
        .MatchWholeWord = False  
        .MatchWildcards = True  
        .MatchSoundsLike = False
        .MatchAllWordForms = False  
    End With  
    Selection.InsertBefore ("(")  
    Selection.InsertAfter (")")  
    Selection.Find.Execute Replace:=wdReplaceAll 
    

Solution

  • Try with following solution:

    With Selection.Find
        .Text = "(No.)( )([1-9]{1;2})"
        .Replacement.Text = "(\3)"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll