none
VBA to search for words in all caps RRS feed

  • Question

  • In Word 2013, I recorded the steps to select words that are in all caps.  The generated code is as follows:

    Sub Macro1()
    '
    ' Macro1 Macro
    '
    '
      Selection.Find.ClearFormatting
      With Selection.Find
        .Text = "[A-Z]{2,}"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
      End With
    End Sub

    While recording, the correct selection is made.  After running the macro, all text is selected, not just the text in all caps.

    What is going wrong?

    Thanks!

    Saturday, May 18, 2013 4:45 PM

Answers

  • As posted, this macro won't do anything at all since the search is only initialized but not executed.

    To perform the search:

    Sub Macro1()
    '
    ' Macro1 Macro
    '
    '
        With Selection.Find
            .ClearFormatting
            .Text = "[A-Z]{2,}"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindAsk
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            .Execute
        End With
    End Sub


    Regards, Hans Vogelaar

    Saturday, May 18, 2013 10:00 PM

All replies

  • As posted, this macro won't do anything at all since the search is only initialized but not executed.

    To perform the search:

    Sub Macro1()
    '
    ' Macro1 Macro
    '
    '
        With Selection.Find
            .ClearFormatting
            .Text = "[A-Z]{2,}"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindAsk
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            .Execute
        End With
    End Sub


    Regards, Hans Vogelaar

    Saturday, May 18, 2013 10:00 PM
  • In addition to what Hans posted, your code doesn't just find words in capitals - but any string containing two or more consecutive capitals.

    As coded, if a Replace was executed, the found strings would be replaced with paragraph breaks. Assuming that is not what you really want, try:

    Sub Demo()
    With Selection.Find
      .ClearFormatting
      .Text = "<[A-Z]{2,}>"
      .Format = False
      .Forward = True
      .MatchWildcards = True
      .Wrap = wdFindAsk
      .Execute
    End With
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Sunday, May 19, 2013 6:49 AM