2015-10-26 106 views
0

我使用此宏替換不同文檔中的某些值,但不替換第一頁頁腳中的文本。我想這是因爲第一頁頁腳與其他頁面不同。我剛開始使用VBA代碼,所以我不知道如何解決這個問題。我會很感激,如果有人能夠爲我修改宏,以便它能夠在第一頁的頁腳中查找和替換值?在Word文檔的第一頁頁腳中查找並替換

Sub DoReplace() 

Const Find1 = "FIND TEXT" 
Const Replace1 = "REPLACE TEXT" 

Const Find2 = "FIND TEXT" 
Const Replace2 = "REPLACE TEXT" 

Dim FilePick As FileDialog 
Dim FileSelected As FileDialogSelectedItems 
Dim WordFile As Variant ' FileName placeholder in selected files loop 
Dim FileJob As String ' Filename for processing 

Dim WorkDoc As Object 
Dim WholeDoc As Range 
Dim FooterDoc As Range 

On Error GoTo DoReplace_Error 

    Set FilePick = Application.FileDialog(msoFileDialogFilePicker) 

    With FilePick 
     .Title = "Choose Report Template" 
     .Filters.Clear 
     .Filters.Add "Word Documents & Templates", "*.do*" 
     .Filters.Add "Word 2003 Document", "*.doc" 
     .Filters.Add "Word 2003 Template", "*.dot" 
     .Filters.Add "Word 2007 Document", "*.docx" 
     .Filters.Add "Word 2007 Template", "*.dotx" 
     .Show 
    End With 

    Set FileSelected = FilePick.SelectedItems 

    If FileSelected.Count <> 0 Then 

     For Each WordFile In FileSelected 

      FileJob = WordFile 

      Set WorkDoc = Application.Documents.Open(FileJob, , , , , , , , , , , False) 

      Set WholeDoc = WorkDoc.Content 
      Set FooterDoc = WorkDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range 

      With FooterDoc 
       .Find.Execute Find1, True, True, , , , True, , , Replace1, wdReplaceAll 
       .Find.Execute Find2, True, True, , , , True, , , Replace2, wdReplaceAll 
      End With 

      With WholeDoc.Find 
       .Execute Find1, True, True, , , , True, , , Replace1, wdReplaceAll 
       .Execute Find2, True, True, , , , True, , , Replace2, wdReplaceAll 

      End With 

      WorkDoc.Save 
      WorkDoc.Close 

     Next 

    End If 

    MsgBox "Completed" 

DoReplace_Exit: 

    Set WholeDoc = Nothing 
    Set FilePick = Nothing 

    Set WorkDoc = Nothing 
    Set FooterDoc = Nothing 

    Exit Sub 

DoReplace_Error: 

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure DoReplace of VBA Document ReplaceMulti" 
    Resume DoReplace_Exit 

End Sub 

回答

0

創建另一個變量並將其他頁腳分配給它。像

Dim footerPage1 as Word.Range 
Set footerPage1 = WorkDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range 

東西但有一個更好的方式去在整個文檔中搜索,而無需瞭解,並指定每個「故事」。首先查找物業的文檔:StoryRanges

這包含將給你一個開始的示例代碼。然後在互聯網上按以下條款進行搜索以詳細瞭解如何使用它:

Word find StoryRanges 
+0

非常感謝您的幫助!它很棒! 我會研究你的建議。再次感謝! – ToMeee

相關問題