Vba word поиск текста по шаблону

Цитата
Сообщение от Lupus
Посмотреть сообщение

что за объект такой Content и чем он отличается от Range ?

Вообще документ состоит из нескольких частей (я все не могу вспомнить):

  1. колонтитулы,
  2. сноски,
  3. надписи,
  4. собственно документ.

Content — это и есть собственно документ.

Что касается Range, то надо различать:

  1. свойство Range;
  2. метод Range.

Метод Range есть только у объекта Document (Activedocument) и Shapes (про Shapes не знаю, ни разу не использовал). С помощью метода можно задавать определённый диапазон, например:

Visual Basic
1
Activedocument.Range(Start:=0, End:=10)

что означает диапазон документа от начала и до десятого знака включительно. Если ничего не указано:

Visual Basic
1
Activedocument.Range

то означает — весь документ. Т.е. в данном случае Range, то же самое, что Content (хотя может разница и есть в чём-то).

В остальных случаях (когда Range не относится к Documents (Activedocument), Range является свойством и с помощью него узнают

порядковый номер символа

(но там путаница большая, если используются в документе кроме символов другие объекты (например, рисунки)) и

содержимое объекта

(например, абзаца):

Visual Basic
1
2
3
4
Sub P3()
'Определение номера символа, когда начинается абзац.
MsgBox ActiveDocument.Paragraphs(1).Range.Start
End Sub
Visual Basic
1
2
3
4
Sub P4()
'Получаем содержимое абзаца.
MsgBox ActiveDocument.Paragraphs(1).Range
End Sub
title ms.prod ms.assetid ms.date ms.localizationpriority

Finding and Replacing Text or Formatting

word

9ab9f4a7-9833-5a78-56b0-56a161480f18

06/08/2019

medium

Finding and replacing is exposed by the Find and Replacement objects. The Find object is available from the Selection object and the Range object. The find action differs slightly depending upon whether you access the Find object from the Selection object or the Range object.

Finding text and selecting it

If the Find object is accessed from the Selection object, the selection is changed when the find criteria is found. The following example selects the next occurrence of the word «Hello.» If the end of the document is reached before the word «Hello» is found, the search is stopped.

With Selection.Find 
 .Forward = True 
 .Wrap = wdFindStop 
 .Text = "Hello" 
 .Execute 
End With

The Find object includes properties that relate to the options in the Find and Replace dialog box. You can set the individual properties of the Find object or use arguments with the Execute method, as shown in the following example.

Selection.Find.Execute FindText:="Hello", _ 
 Forward:=True, Wrap:=wdFindStop

Finding text without changing the selection

If the Find object is accessed from a Range object, the selection is not changed but the Range is redefined when the find criteria is found. The following example locates the first occurrence of the word «blue» in the active document. If the find operation is successful, the range is redefined and bold formatting is applied to the word «blue.»

With ActiveDocument.Content.Find 
 .Text = "blue" 
 .Forward = True 
 .Execute 
 If .Found = True Then .Parent.Bold = True 
End With

The following example performs the same result as the previous example, using arguments of the Execute method.

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="blue", Forward:=True 
If myRange.Find.Found = True Then myRange.Bold = True

Using the Replacement object

The Replacement object represents the replace criteria for a find and replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box (Edit menu).

The Replacement object is available from the Find object. The following example replaces all occurrences of the word «hi» with «hello». The selection changes when the find criteria is found because the Find object is accessed from the Selection object.

With Selection.Find 
 .ClearFormatting 
 .Text = "hi" 
 .Replacement.ClearFormatting 
 .Replacement.Text = "hello" 
 .Execute Replace:=wdReplaceAll, Forward:=True, _ 
 Wrap:=wdFindContinue 
End With

The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. To find and replace formatting, set the find and replace text to empty strings («») and set the Format argument of the Execute method to True. The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).

With ActiveDocument.Content.Find 
 .ClearFormatting 
 .Font.Bold = True 
 With .Replacement 
 .ClearFormatting 
 .Font.Bold = False 
 End With 
 .Execute FindText:="", ReplaceWith:="", _ 
 Format:=True, Replace:=wdReplaceAll 
End With

[!includeSupport and feedback]

I am trying to help someone automate some very simple text editing in Microsoft Word using VBA.

One desired change to to remove commas that are embedded in numbers while leaving other commas alone. For example:

I like apples, pears, and plums.  See 1,234,567

would become:

I like apples, pears, and plums.  See 1234567

The code looks for a digit followed by a comma followed by a digit. To remove a comma between two digits, the current code loops over all 100 possible cases from 0,0 to 9,9 and does a Find/Replace on each case. So 0,0 becomes 00. Here is the current code:

Sub FindAndReplace()

Dim rng As Range, sFind As String, sRep As String
Dim i As Long, j As Long

For i = 0 To 9
    For j = 0 To 9
        sFind = i & "," & j
        sRep = i & j
        For Each rng In ActiveDocument.StoryRanges
            With rng.Find
                .Text = sFind
                .Replacement.Text = sRep
                .Wrap = wdFindContinue
                .Execute Replace:=wdReplaceAll
            End With
        Next rng
        Next j
    Next i
lbl_Exit:
Exit Sub

I am certain that all this looping over i and j is completely unnecessary and this can be done with a simple wildcard pattern Find, but I don’t know enough about the Word Object model to implement this.

UPDATE:

The RexEx solution worked very well. I also worked out a wildcard solution:

Sub CommaKiller()
    Dim rngStory As Range

        For Each rngStory In ActiveDocument.StoryRanges
            With rngStory.Find
                .MatchWildcards = True
                .Text = "([0-9]),([0-9])"
                .Replacement.Text = "12"
                .Wrap = wdFindContinue
                .Execute Replace:=wdReplaceAll
            End With
        Next rngStory
End Sub

Word VBA Find

This example is a simple word macro find the text “a”:

Sub SimpleFind()

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "a"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
End Sub

Find and Replace

This simple macro will search for the word “their” and replace it with “there”:

Sub SimpleReplace()

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "their"
        .Replacement.Text = "there"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Find and Replace Only in Selection

This VBA macro will find and replace text in a selection. It will also italicize the replaced text.

Sub ReplaceInSelection()
'replaces text JUST in selection . in adittion it makes replaced text italic
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "their"

        With .Replacement
            .Font.Italic = True
            .Text = "there"
        End With

        .Forward = True
        .Wrap = wdFindStop    'this prevents Word from continuing to the end of doc
        .Format = True 'we want to replace formatting of text as well
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

This line of code prevents VBA from continuing to the end of the Word document:

.Wrap = wdFindStop    'this prevents Word from continuing to the end of doc

This line of code indicates to replace the formatting of the text as well:

.Format = True 'we want to replace formatting of text as well

Find and Replace Only In Range

Instead of replacing text throughout the entire document, or in a selection, we can tell VBA to find and replace only in range.  In this example we defined the range as the first paragraph:

Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
Sub ReplaceInRange()
'replaces text JUST in range [in this example just in the first paragraph]
Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
 oRange.Find.ClearFormatting
    oRange.Find.Replacement.ClearFormatting
    With oRange.Find
        .Text = "their"
        .Replacement.Text = "there"
        .Forward = True
        .Wrap = wdFindStop 'this prevent Word to continue to the end of doc
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    oRange.Find.Execute Replace:=wdReplaceAll
End Sub

Word Find and Replace

The Microsoft Word Find and Replace feature is very powerful and a great time saver for the more skilled user. You can use Find and Replace to locate exact words, phrases and even patterns matching various scenarios.

Let us start with exploring how to do a regular Find and Replace in Word.

Click the Find or Replace buttons in the Home ribbon Editing section

Find and Replace in Word - Replace Button
If you want to Find a word or sentence in your Word file go to the Home ribbon tab and go to the Editing section.

  • If you want to Find click Find
  • If you want to Find and Replace click Replace
  • This will open the Find and Replace window.

    You can also use the CTRL+F keyboard shortcut to Find and the CTRL+H keyboard shortcut to do a Find and Replace.

    If you click More > > you will see the full set of options below:
    Find and Replace expanded window
    The following options are available:

    • Match case – will only find words/sentences that match the letter case (e.g. A vs a)
    • Find whole words only – will only find whole words (if looking for “ate” will only match ” ate “ and not “late”)
    • Use wildcards – allows you to use wildcards (click the Special button for list of wildcard special characters that can be used
    • Sounds like – matches expressions that sound like provided text
    • Find all word forms – matches all words/sentences that match a word form (e.g. “doyle” will also match “doyl” as it sounds similar)
    • Match prefix – match text matching a prefix of a word
    • Match suffix – match text matching a suffixof a word
    • Ignore punctuation characters – will ignore punctionation
    • Ignore white-space characters – will ignore white-space (” “)

    Provide a word, sentence and/or wildcard special characters

    Provide a word/sentence you want to Find in the Find what text field and the word/sentence you want to replace it with in the Replace with text field.

    Below and explanation of key buttons used to Find or Replace text:
    Find and Replace fields explained
    Although Find and Replace is a basic and very easy to use function it is often underestimated. Especially that many users do not know that you can easily use wildcards to replace more complex text patterns.

    Using Wilcards

    Word Wildcard Special Characters
    You can also you wildcards to replace various complex patterns such as sequences of numbers or specific number of occurances, letter cases, characters use to replace any characters and much more. To use wilcards click More > > and select the Use wilcards checkbox.

    On the right you should see all available wildcard characters.

    For more information on Special Characters that can be used in Wildcard Find and Replace read this

    Let us explore some example common scenarios below:

    Match any word made of A-Z characters, any letter case

    <[A-z]@>

    This matches any single word that contains A-z letters.
    The < character indicate the beginning, while > the end of a word. The [A-z] brackets indicate a series of characters, using the hyphen allows you specify the whole range of A-z letters. Lastly the @ character indicates that the previous expression may repeat 0 to any number of times.

    Match an email from the .com domain

    <[A-z,0-9]@@[A-z,0-9]@.com>

    This matches only emails with A-z letters and 0-9 numbers in their login and domain name. Again the [A-z,0-9] bracket specifies we are listing several ranges of acceptable characters, following this with the @ characters tells that any number of these characters may appear. To use the @ character explicitly we need to escape it with a backslash . We use the similar patter for the domain name. Finally notice again I am using < and > to indicate the beginning or end of a word as emails are not separated by spaces.

    Match a phone number split with hyphens

    [0-9]@-[0-9]@-[0-9]@

    The above matches any 3 series of digits separated by hyphens.

    Using Wildcards to Capture and Replace text

    In some cases you will want to not only capture a pattern but replace it with part of its content. For this you need to use Expressions (). Expressions let you mark a specific group in the “Find what” text field, that you want to reuse in your “Replace with” text field. Below a simple example:

    Example: Switch places of 2 numbers

    In this example we have a pattern of numbers separated by hyphens. Let us assume we want to switch places of these two 3-digit numbers.
    Text:

    Some text 123-456, some other text 789-012.
    Something else 345-678

    Find what:

    ([0-9]{3})-([0-9]{3})

    Replace with:

    -

    The resulting Text:

    Some text 456-123, some other text 012-789.
    Something else 678-345

    Example: Replace Email domain

    Imagine you want to replace an email domain from yahoo to gmail on all emails in your Word document. If you didn’t know Expressions you would use wildcards to find a match an manually replace all such cases. However below an example that will replace this automatically:

    All Expressions () are numbered by the sequence in which they are used. This allows us to reference the first part of the email by using the backslash and number 1.

    VBA Find and Replace

    You can also execute a Find and Replace sequence using a VBA Macro:

    Find a single match

    The below procedure will print out all occurances of “Find Me” phrases.

    ActiveDocument.Content.Select
    With Selection.Find
        .Text = "Find Me"
        .Forward = True
        .Execute
    End With
     
    If Selection.Find.Found Then
          Debug.Print "Found: " & Selection.Range 'Print the found match 
    Else
          Debug.Print "Not Found"
    End If
    

    Find all matches

    Below VBA macro will find all emails in a Word document with their mailto hyperlinks. This is a good example of fixing hyperlinks in Word documents.

    ActiveDocument.Content.Select
    Do
      With Selection.Find
          .Text = "<[A-z,0-9]@@[A-z,0-9]@.com>"
          .MatchWildcards = True
          .Forward = True
          .Execute
      End With
     
      If Selection.Find.Found Then
          ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="mailto:" & Selection.Range
      Else
          Exit Do 'If not found then end the loop
      End If
    Loop
    

    Conclusions

    Here are my main takeaways from using Find and Replace in Microsoft Word

Понравилась статья? Поделить с друзьями:
  • Vba word поиск текста в таблице
  • Vba word поиск строки
  • Vba word поиск в строке
  • Vba word поиск в документе
  • Vba word подстановочные символы