vba - 在 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
解决方案
这应该适合你。看看你的代码,
- 我看到这个标签将始终存在于表格中。“.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
推荐阅读
- javascript - 摩纳哥编辑器自动完成功能在哪里?
- c - 为什么 ALSA 播放速度过快?
- python - 用更少的内存存储/加载巨大的numpy数组
- bash - 如何引用 for 循环的所有先前迭代
- php - 如何使用自动登录脚本 (PHP) 转到特定的 cPanel 页面
- alpacajs - 如何根据羊驼中的条件显示复选框?
- docker - 安装/附加卷后如何在 docker 容器中添加文件?
- c# - 在 Visual Studio Code 中设置 .NET Core MVC Web 应用
- python-2.7 - 无法使用硒单击提交按钮
- io - Page Fault 和 I/O 之间有什么关系?