2017-04-04 80 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