2017-04-04 81 views
1

当我尝试运行它时,我的代码中出现运行时错误13(类型不匹配)。 我试图通过Excel中的标题内部替换打开的Word文档中的文本。在标题VBA中替换文本的错误Excel

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 
0

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

+0

我改变了我行: lngJunk = WordDoc.ActiveDocument.Sections(1).Headers(1).Range.StoryType 这引发了我的错误在这里 (错误438对象没有按支持此属性或方法) – ante011