2013-12-12 82 views
0

我有以下VBA代碼,它在所有活動文檔中查找佔位符文本(FindText)並用圖像替換文本。當文本位於文檔正文中時,此代碼正常工作;但是,如果佔位符文本位於文檔標題中,則文本不會被圖像替換。Microsoft Word宏VBA用文檔標題中的圖像替換文本

我的問題是,如果文本位於文檔的標題中,如何用圖像替換佔位符文本?

Sub InsertImagesAllDocuments() 

Dim n, c As Integer 
n = Application.Documents.Count 
c = 1 

Dim r As range 

Windows(c).Activate 


Do 
Dim imageFullPath As String 
Dim FindText As String 
imageFullPath = "C:\Logo.jpg" 
FindText = "TextPlaceholder" 
    With Selection 
    .HomeKey Unit:=wdStory 

    With .Find 
     .ClearFormatting 
     .text = FindText 
     ' Loop until Word can no longer 
     ' find the search string, inserting the specified image at each location 
     Do While .Execute 
      Selection.MoveRight 
      Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True 
     Loop 

    End With 
End With 


    c = c + 1 

    On Error Resume Next 
    Windows(c).Activate 

Loop Until c > n 



End Sub 

回答

2

您將希望打開標題以替換文本。你可以這樣做,用這行代碼

ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader 
'now the header is accessible, run your code 
    With Selection 
    .HomeKey Unit:=wdStory 

     With .Find 
     .ClearFormatting 
     .text = FindText 
     ' Loop until Word can no longer 
     ' find the search string, inserting the specified image at each location 
     Do While .Execute 
      Selection.MoveRight 
      Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True 
     Loop 

    End With 
End With 
+1

謝謝。運作良好。我只是關閉了視圖以及ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument謝謝 – user1783736

相關問題