Annoying issue with c suggestion in VBA

I use this function to replace some access strings in a text document. This function works very well.

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)
    With doc.Content.Find
        .Text = after 
        .Replacement.Text = before 
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute replace:=wdReplaceAll
        Else
            .Execute replace:=wdReplaceOne
    End If
    End With
End Sub

But ... I do not know why, if I rewrote the function in this way, it will stop working. There is no error or warning, but no replacement is made.

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)
    doc.Content.Find.Text = after 
    doc.Content.Find.Replacement.Text = before 
    With doc.Content.Find
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute replace:=wdReplaceAll
        Else
            .Execute replace:=wdReplaceOne
        End If
    End With
End Sub

Can someone explain what the difference is between the two fragments or why the second is not working properly? Thank!

+3
source share
2 answers

The Find property returns a Find object every time you call it. So in the second code snippet you

  • Create a Find object and set its Text property
  • Find Replacement.Text

Text Replacement.Text. ,

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)

    Dim fnd As Find

    Set fnd = doc.Content.Find

    fnd.Text = after
    fnd.Replacement.Text = before
    With fnd
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute Replace:=wdReplaceAll
        Else
            .Execute Replace:=wdReplaceOne
        End If
    End With
End Sub
+7

? . , - , , ?

( , End If , , - )

+1

Source: https://habr.com/ru/post/1776268/


All Articles