0
votes

Im trying to create VBA macro that copy a variable entered by user and search for a specific field in text word and replace it and I tried many codes in stack overflow and other forum but i didn't succeed The code below work correctly but it doesn't replace the word , the code search for that field and put the variable next to it . if someone have a solution :D

Sub CreateNewWordDoc()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
Set wrdDoc = wrdApp.Documents.Open("D:\pfe\DECfinal1.doc")
With wrdDoc
.Application.Selection.Find.Text = "Nombre d'alésage"
.Application.Selection.Find.Execute
.Application.Selection = Sheets("Dec").Range("A2")

End With

End Sub
1
It works just fine for me.Siddharth Rout
It works i know but I want to replace that text with my variable not to put the variable next to it . for example When the there is a variable in excel and I run the macro , he seach for """ Nombre d'alésage """ and replace it (( NoT COPY NEXT TO IT )) with the variable i added in exceluser7755666

1 Answers

0
votes

Like I said your code works for me. But to be on a safer side, use objects to work with it and do a direct search and replace. See this

Sub CreateNewWordDoc()
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document

    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True

    Set wrdDoc = wrdApp.Documents.Open("C:\Users\Siddharth\Desktop\DECfinal89.doc")

    With wrdDoc
        For Each rngStory In .StoryRanges
            Do
                With rngStory.Find
                    .Text = "Nombre d'alésage"
                    .Replacement.Text = Sheets("Dec").Range("A2")
                    .Wrap = wdFindContinue
                    .Execute Replace:=wdReplaceAll
                End With
                Set rngStory = rngStory.NextStoryRange
            Loop Until rngStory Is Nothing
          Next
    End With
End Sub