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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.