【问题标题】:VBA insert picture and legends word 2010VBA插入图片和图例word 2010
【发布时间】:2015-10-16 02:00:11
【问题描述】:

一个看起来很简单但不能完全按照我想要的方式工作的 vba 脚本。 我的脚本在当前文档中插入图片(PNG 文件),每张图片后面都有一个标题,即文件名。

所以要插入我使用的图像:

Selection.InlineShapes.AddPicture FileName: = sFile
Selection.TypeParagraph

并在我使用后插入文本:

Set Opar = ActiveDocument.Paragraphs.Add
oPar.Range.Text = sFile
oPar.Range.Style = " Normal"

问题是图片都在文档开头,顺序倒序排列(最后插入的图片在文档中最先出现),图例都在文档末尾。

发生了什么事?

【问题讨论】:

  • 您是否尝试在插入后移动您的选择?
  • 您的代码不会发生这种情况,但无论如何,您可以尝试先移动选择,然后像@Cptn_Hammer 所说的那样重新执行您的代码。
  • 你能解释一下“移动选择”吗?是通过代码完成的吗?
  • 是的,在您的代码中,您可以执行诸如 Selection.EndKey Unit:=wdStory 之类的操作,这会将所选内容移动到文档的末尾并以正确的顺序插入。每次插入后调用 Selection.EndKey Unit:=wdStory。
  • 这里是插入图片和标题的代码,看看:stackoverflow.com/questions/35359351/…

标签: vba ms-word


【解决方案1】:

@Boro:直接使用对象模型比尝试强制选择(模仿用户操作)更有效。没有单一的方法可以实现你所描述的,所以我将展示我的偏好:

Dim ils as Word.InlineShape
Dim rng as Word.Range
'Starting with current sel, but this could also be a Range...
Set ils = Selection.InlineShapes.AddPicture(FileName: = sFile)
Set rng = ils.Range
'Move the focus AFTER the picture
rng.Collapse wdCollapseEnd
'new para, text, followed by new para
rng.Text = vbCr & sFile & vbCr
rng.Style = wdStyleNormal
'focus in last para inserted by code
rng.Collapse wdCollapseEnd
'Do other things with the Range...
'Leave cursor there for user to work
rng.Select

我的方法的关键是折叠范围,无论是起点还是终点。可以将其想象为按向左或向右箭头键以将选择减少为闪烁的光标。除非你可以有任意数量的 Ranges(但只有一个 Selection)并且不会在屏幕上跳来跳去。

【讨论】:

  • 这太完美了:太棒了!并感谢您的详细解释。很有帮助。
  • 如果某个答案对您有帮助,请点击旁边的复选标记接受它。欢迎使用 Stack Overflow!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 2013-05-11
相关资源
最近更新 更多