我试图创建VBA宏,复制用户输入的变量并在文本字中搜索特定字段并替换它,我在堆栈溢出和其他论坛中尝试了很多代码,但我没有成功 下面的代码工作正常,但它不会替换单词,代码搜索该字段并将变量放在它旁边。如果有人有解决方案: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
答案 0 :(得分:0)
就像我说你的代码适合我。但为了更安全,使用对象来处理它并直接搜索和替换。见这个
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