Vba word поиск в строке

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Find.Execute method (Word)

vbawd10.chm162529724

vbawd10.chm162529724

word

Word.Find.Execute

3b607955-0e82-aa13-dad1-7a5069a57b9d

06/08/2017

medium

Find.Execute method (Word)

Runs the specified find operation. Returns True if the find operation is successful. Boolean.

Syntax

expression.Execute (FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)

expression Required. A variable that represents a Find object.

Parameters

Name Required/Optional Data type Description
FindText Optional Variant The text to be searched for. Use an empty string («») to search for formatting only. You can search for special characters by specifying appropriate character codes. For example, «^p» corresponds to a paragraph mark and «^t» corresponds to a tab character.
MatchCase Optional Variant True to specify that the find text be case-sensitive. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu).
MatchWholeWord Optional Variant True to have the find operation locate only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box.
MatchWildcards Optional Variant True to have the find text be a special search operator. Corresponds to the Use wildcards check box in the Find and Replace dialog box.
MatchSoundsLike Optional Variant True to have the find operation locate words that sound similar to the find text. Corresponds to the Sounds like check box in the Find and Replace dialog box.
MatchAllWordForms Optional Variant True to have the find operation locate all forms of the find text (for example, «sit» locates «sitting» and «sat»). Corresponds to the Find all word forms check box in the Find and Replace dialog box.
Forward Optional Variant True to search forward (toward the end of the document).
Wrap Optional Variant Controls what happens if the search begins at a point other than the beginning of the document and the end of the document is reached (or vice versa if Forward is set to False). This argument also controls what happens if there is a selection or range and the search text is not found in the selection or range. Can be one of the WdFindWrap constants.
Format Optional Variant True to have the find operation locate formatting in addition to, or instead of, the find text.
ReplaceWith Optional Variant The replacement text. To delete the text specified by the Find argument, use an empty string («»). You specify special characters and advanced search criteria just as you do for the Find argument. To specify a graphic object or other nontext item as the replacement, move the item to the Clipboard and specify «^c» for ReplaceWith.
Replace Optional Variant Specifies how many replacements are to be made: one, all, or none. Can be any WdReplace constant.
MatchKashida Optional Variant True if find operations match text with matching kashidas in an Arabic-language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchDiacritics Optional Variant True if find operations match text with matching diacritics in a right-to-left language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchAlefHamza Optional Variant True if find operations match text with matching alef hamzas in an Arabic-language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchControl Optional Variant True if find operations match text with matching bidirectional control characters in a right-to-left language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchPrefix Optional Variant True to match words beginning with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box.
MatchSuffix Optional Variant True to match words ending with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box.
MatchPhrase Optional Variant True ignores all white space and control characters between words.
IgnoreSpace Optional Variant True ignores all white space between words. Corresponds to the Ignore white-space characters check box in the Find and Replace dialog box.
IgnorePunct Optional Variant True ignores all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box.

Return value

Boolean

Remarks

If MatchWildcards is True, you can specify wildcard characters and other advanced search criteria for the FindText argument. For example, «*(ing)» finds any word that ends in «ing».

To search for a symbol character, type a caret (^), a zero (0), and then the symbol’s character code. For example, «^0151» corresponds to an em dash (—).

Unless otherwise specified, replacement text inherits the formatting of the text it replaces in the document. For example, if you replace the string «abc» with «xyz», occurrences of «abc» with bold formatting are replaced with the string «xyz» with bold formatting.

Also, if MatchCase is False, occurrences of the search text that are uppercase will be replaced with an uppercase version of the replacement text, regardless of the case of the replacement text. Using the previous example, occurrences of «ABC» are replaced with «XYZ».

Example

This example finds and selects the next occurrence of the word «library».

With Selection.Find 
    .ClearFormatting 
    .MatchWholeWord = True 
    .MatchCase = False 
    .Execute FindText:="library" 
End With

This example finds all occurrences of the word «hi» in the active document and replaces each occurrence with «hello».

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="hi", _ 
    ReplaceWith:="hello", Replace:=wdReplaceAll

[!includeSupport and feedback]

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

Цитата
Сообщение от 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

I am not proud of this solution ….

I look for a string in a word document and publish the result in a table of another word document …
The table is divided into 3 parts: in the center the string I searched for, in the first column «x number of words» to the left of the string and in the third column «y number of words» to the right of the searched string.
But it’s very slow … better solutions?
Thank you

Sub Cerca(Parola, Destinazione)

Dim rng1 As Range
Dim rng2 As Range
Dim rngFound As Range
Dim Prima As Long
Dim Dopo As Long
Dim PosizioneAttuale As Long
Dim strSinistra As String
Dim strCentro As String
Dim strDestra As String
Dim UltimaRiga As Long
Dim Ciclo As Long
Dim Sicurezza As Long

Selection.HomeKey Unit:=wdStory
'Selection.Find.ClearFormatting

 With Selection.Find
     .Text = Parola
    ' .Replacement.Text = "Provo"
     .Forward = True
     .Wrap = wdFindStop
     .IgnorePunct = True
     .MatchWholeWord = ParoleIntere
     .ClearFormatting
     .Format = False
     Do While .Execute() = True

         DoEvents

         PosizioneAttuale = Selection.Start


         'SI CONTROLLA A DESTRA
         Ciclo = 0
         Sicurezza = 0
         Do
            'DoEvents
            Sicurezza = Sicurezza + 1
            Selection.MoveRight Unit:=wdWord, Count:=1
            If InStr(1, ".,;:-_/!'()" & Chr(34) & vbCrLf, Trim(Selection.Range.Words.Item(1)), vbTextCompare) = 0 Then
                Ciclo = Ciclo + 1
            End If
            If Sicurezza > 100 Then
                'Debug.Print "esco con exit do"
                'Selection.MoveLeft Unit:=wdWord, Count:=501
                Exit Do 'nel caso entri in loop per qualche motivo
            End If
         Loop Until Ciclo = ParoleDopo Or Selection.Range.Start = ActiveDocument.Range.End

         Selection.MoveRight Unit:=wdWord, Count:=1
         Set rng2 = Selection.Range

         Selection.Start = PosizioneAttuale


         'SI CONTROLLA A SINISTRA

         Ciclo = 0
         Sicurezza = 0
         Selection.MoveLeft Unit:=wdWord, Count:=1
         Do
            'DoEvents
            Sicurezza = Sicurezza + 1
            Selection.MoveLeft Unit:=wdWord, Count:=1
            If InStr(1, ".,;:-_/!'()", Trim(Selection.Range.Words.Item(1)), vbTextCompare) = 0 Then
                Ciclo = Ciclo + 1
            End If
            If Sicurezza > 100 Then
                Debug.Print "esco con exit do"
                'Selection.MoveRight Unit:=wdWord, Count:=501
                Exit Do 'nel caso entri in loop per qualche motivo
            End If
         Loop Until Ciclo = ParolePrima Or Selection.Range.Start = ActiveDocument.Range.End



         'Selection.MoveLeft Unit:=wdWord, Count:=ParolePrima + 1
         Set rng1 = Selection.Range

         Prima = rng1.Start
         Dopo = rng2.Start

         If Dopo > Prima Then
                 Set rngFound = ActiveDocument.Range(Prima, Dopo)

                 strTheText = rngFound.Text



                 'ScriviFile Left(strTheText, Prima) & Chr(9) & Parola & Chr(9) & Mid(strTheText, Dopo)
                 strSinistra = Left(strTheText, PosizioneAttuale - Prima)
                 strCentro = Parola
                 Prima = PosizioneAttuale + Len(Parola)
                 If Prima = -1 Then Prima = 0
                 strDestra = Right(strTheText, Dopo - Prima)


                 Selection.Start = PosizioneAttuale
                 Selection.MoveRight Unit:=wdWord, Count:=1

                 'scrivo nella tabella del foglio destinazione
                  Documents(Destinazione).Tables(1).Rows.Add
                  UltimaRiga = Documents(Destinazione).Tables(1).Rows.Count
                      Documents(Destinazione).Tables(1).Cell(UltimaRiga, 1).Range.InsertAfter strSinistra
                      Documents(Destinazione).Tables(1).Cell(UltimaRiga, 2).Range.InsertAfter strCentro
                      Documents(Destinazione).Tables(1).Cell(UltimaRiga, 3).Range.InsertAfter strDestra



         End If

     Loop
 End With
End Sub

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