在标题VBA Excel中replace文本时出错

当我尝试运行它时,我的代码中出现运行时错误13( types不匹配 )。 我试图通过Excel中,在标题中replace打开的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 

你有“WordApp.ActiveDocument”似乎很尴尬。 当你可能需要的是“WordDoc”。 在你的'lngJunk'和'For Each'行中。

我相信你正在尝试做一个VBAsearch和replace。 我们使用了一系列function,经过多年的改进,我们使用了以下内容。 这纯粹是执行search和replace的function。

 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