Microsoft Word宏VBA使用文档标题中的图像替换文本

时间:2013-12-12 19:10:05

标签: vba ms-word word-vba

我有以下VBA代码,在所有活动文档中找到占位符文本(FindText),并用图像替换文本。当文本在文档正文中时,此代码可以正常工作;但是,如果占位符文本位于文档标题中,则文本不会替换为图像。

我的问题是,如果文本在文档的标题中,如何用图像替换占位符文本?

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

1 个答案:

答案 0 :(得分: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