当我的代码从Excel执行时,它将打开一个Word文档,并且可以用从Excel文件中获取的给定值替换word doc中的字符串,但是它当前不会替换文本框中的任何文本在Word文档中。
这是我的代码(我从之前的帖子中获取) -
For Each itm In arrNames
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\Test\Desktop\Test.docx"
With objWord
.Activate
With objWord.Selection.Find
.Text = "Sheep"
.Replacement.Text = itm
.Forward = True
.Wrap = 2
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchSoundsLike = False
.MatchWildcards = True
.Execute Replace:=2
End With
End With
objWord.Application.ActiveDocument.SaveAs ("C:\Users\Test\Desktop\ReportPage\" & itm & ".doc")
Next itm
我是否还需要传递给With语句的其他参数才能替换文本框中的文本?
答案 0 :(得分:0)
我能够找到解决方案。
这是代码 -
Dim objWord2 As Object
Set objWord2 = CreateObject("Word.Application")
objWord2.Visible = True
objWord2.Documents.Open "C:\Users\kmccorma\Desktop\FRONTCOVER.doc"
'Iterate round a list of names
For Each itm In arrNames
Dim rngStory As Word.Range
'Iterate through all story types in the current document
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
Dim strText As String
' Get the text from the current TextBox
strText = rngStory.Text
'Check if the current text box contains the string you are looking for
If InStr(1, strText, "SearchText") Then
'Overwrite the text in the TextBox
rngStory.Text = itm
End If
'Get next linked story (if any)
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
If itm & "X" <> "X" Then
ActiveDocument.SaveAs ("C:\Users\kmccorma\Desktop\FrontCover\" & itm & ".doc")
End If
Next itm