Reputation: 99
I get run-time error 13 (Type Mismatch) on my code when I try to run it. I'm trying to replace a text in a opened Word document through Excel, inside the header.
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
Upvotes: 1
Views: 403
Reputation: 59
I believe you are trying to do a VBA search and replace. We have a BUNCH of functions that we use, and after many years of refinement, the following is what we use. It's purely the function that performs a search and replace.
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
Upvotes: 1
Reputation: 59
It seems awkward that you have "WordApp.ActiveDocument." when what you probably need is "WordDoc." in your 'lngJunk' and 'For Each' lines.
Upvotes: 0