首页 > 解决方案 > 在 Word 文档的表格中搜索文本并将其替换为图像

问题描述

我需要用<tag>filename123</tag>图像替换 Word 文档中表格内的每个出现D:\images\filename123.jpg(每个标签内容都不同)。我使用从另一个答案复制的以下代码,它可以很好地执行搜索命令,但我无法使替换行正常工作。怎么了?

Sub Demo()
Dim StrOut As String
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "\<tag\>*\</tag\>"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    If .Information(wdWithInTable) = True Then
      StrOut = Split(Split(.Text, ">")(1), "<")(0)
    End If
    .Collapse wdCollapseEnd
    ' the following line yields "Run-time error 9"
    .InlineShapes.AddPicture FileName:= _
    "D:\images\" & StrOut, LinkToFile:=False _
    , SaveWithDocument:=True
    .Text = ""
    .Find.Execute
  Loop
End With
End Sub

标签: vbams-word

解决方案


这应该适合你。看看你的代码,

  • 我看到这个标签将始终存在于表格中。“.Information(wdWithInTable)”
  • 我还将“拆分”更改为“替换”以避免使用索引。
  • 您在图像代码中缺少文件扩展名,因此.png 替换为您拥有的任何格式的图像
Sub Demo()
Dim StrOut As String
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "\<tag\>*\</tag\>"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    If .Information(wdWithInTable) = True Then
      StrOut = Replace(Replace(.Text, "<tag>", ""), "</tag>", "")
    End If
    .Collapse wdCollapseEnd
    ' the following line yields "Run-time error 9"
    .InlineShapes.AddPicture FileName:= _
    "C:\Users\xyz\" & StrOut + ".png", LinkToFile:=False _
    , SaveWithDocument:=True
    .Text = ""
    .Find.Execute
  Loop
End With
End Sub

推荐阅读