You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Word VBA在文档所有页面中插入图片?

给Word文档每一页插入图片的VBA代码

以下是修改后的VBA代码,可实现给Word文档的每一页插入指定图片:

Sub InsertImageOnEveryPage()
    Dim oILS As InlineShape, oShp As Shape
    Dim pageNum As Integer
    Dim imgPath As String
    
    ' 替换为你的图片实际路径
    imgPath = "C:\Users\" & LCase(Environ("UserName")) & "\Desktop\SubEscritorio3\Ejercicios Matemáticas\Barra.png"
    
    ' 遍历文档所有页面
    For pageNum = 1 To ActiveDocument.ActiveWindow.Panes(1).Pages.Count
        ' 定位到当前页开头
        ActiveDocument.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=pageNum
        
        ' 插入图片并转为浮动形状
        Set oILS = Selection.InlineShapes.AddPicture(FileName:=imgPath, _
            LinkToFile:=False, SaveWithDocument:=True)
        Set oShp = oILS.ConvertToShape
        
        ' 设置图片格式与固定位置
        With oShp
            .WrapFormat.Type = wdWrapBehind ' 置于文字下方
            .Left = -55 ' 水平位置
            .Top = 471.1 ' 垂直位置
            .Height = 21.5 ' 高度
            .Width = 522 ' 宽度
            ' 绑定位置到页面,防止内容变动后移位
            .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
            .RelativeVerticalPosition = wdRelativeVerticalPositionPage
        End With
    Next pageNum
End Sub

关键改动说明

  • 加入For...Next循环,遍历文档的每一页,实现批量插入
  • 用GoTo方法定位到每一页的开头,确保图片插入到对应页面
  • 新增位置绑定设置,把图片的相对位置固定到页面,避免文档内容修改后图片乱跑
  • 将图片路径提取为单独变量,方便后续修改路径

注意事项

  • 确认图片路径正确,路径中的特殊字符(如示例里的西班牙语词汇)Word可正常识别
  • 如果文档包含分节符,需根据实际分节情况调整遍历逻辑
  • 运行代码前建议先保存文档,避免意外丢失内容

内容的提问来源于stack exchange,提问作者Ulises Antonio Chávez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:12:04