在Word文档的表格内搜索文本,然后将其替换为图像

时间:2019-05-15 16:26:25

标签: vba ms-word

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

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

1 个答案:

答案 0 :(得分:1)

这应该为您工作。看看您的代码,

  • 我看到这个标签将始终存在于表中。 “。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\jx00938\" & StrOut + ".png", LinkToFile:=False _
    , SaveWithDocument:=True
    .Text = ""
    .Find.Execute
  Loop
End With
End Sub