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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20552141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:55:46  来源:igfitidea点击:

Microsoft Word Macro VBA Replace text with image in document header

vbams-wordword-vba

提问by user1783736

I have the following VBA code that finds the placeholder text (FindText) in all active documents and replaces the text with an image. This code works fine when the text is in the document body; However, if the placeholder text is in the document header, the text does not get replaced with the image.

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

My question is, How do I replace the placeholder text with the image if the text is in the header of the document?

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

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

回答by Sorceri

you will want to open the header in order to replace the text. You can do so with this line of code

您将需要打开标题以替换文本。你可以用这行代码

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