当我尝试运行它时,我的代码出现运行时错误13( Type Mismatch )。 我正在尝试通过Excel中的标题替换已打开的Word文档中的文本。
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(myPath & "\Armaturförteckning.docx")
' Ändrar i Armaturförteckningen
Dim rngStory As Range
Dim lngJunk As Long
'Fix the skipped blank Header/Footer problem as provided by Peter Hewett
lngJunk = WordApp.ActiveDocument.Sections(1).Headers(1).Range.StoryType
'Iterate through all story types in the current document
For Each rngStory In WordApp.ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
With WordApp.rngStory.Find
.Text = "ELESTATUS01"
.Replacement.Text = "I'm found"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
'Get next linked story (if any)
Set rngStory = WordApp.rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
' Stänger dokumentet
WordApp.Documents.Save
WordApp.ActiveDocument.Close
答案 0 :(得分:1)
我相信你正在尝试进行VBA搜索和替换。我们使用了一系列功能,经过多年的改进,以下是我们使用的功能。它纯粹是执行搜索和替换的功能。
Function SimpleSearchAndReplace(SomeDocument As Word.Document, SearchString As String, ReplaceString As String)
With SomeDocument.Content.Find
.Text = SearchString
.Replacement.Text = ReplaceString
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Function
答案 1 :(得分:0)
你有“WordApp.ActiveDocument”似乎很尴尬。什么时候你可能需要的是“WordDoc”。在你的'lngJunk'和'For Each'系列中。