2013-12-12 81 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

相关问题