vba - 如何以编程方式将 word 文档中的文本框移动到另一个页面
问题描述
以下 VBA 代码选择 word 文档中包含特定文本的文本框。如何以编程方式将每个文本框移动到另一个页面(比如说第一页),保留它相对于页面的位置。原始文本框绝对定位于它们所在的页面。
Sub searchTexboxes()
'
' searchTexboxes Macro
'
'
Dim shp As Shape
Dim sTemp As String
Dim nrTextboxes As Integer
nrTextboxes = 0
For Each shp In ActiveDocument.Shapes
If shp.Type = msoTextBox Then
shp.Select
Selection.ShapeRange.TextFrame.TextRange.Select
sTemp = Selection.Text
sTemp = Left(sTemp, 1)
If sTemp = "." Then
nrTextboxes = nrTextboxes + 1
End If
End If
Next
MsgBox ("Found " & nrTextboxes & " textboxes.")
End Sub
解决方案
以下代码适用于我。
真正做到这一点的唯一方法(除了从头开始重新创建文本框)是复制/粘贴。这将贯穿所有格式。
这种方法的关键方面:
设置目标页面:由于 Word 的动态布局行为,Word 没有“页面”对象。Selection.GoTo
是获取页面的最简单方法。由于文本框是相对于页面进行格式化的,因此锚点附加在页面的哪个位置并不重要。(除非有很多后续编辑可能会将锚定范围推到不同的页面。)因此,此代码将第一段的范围指定为锚点。
识别要复制的文本框:无需选择文本框即可使用其内容。文本可以从 中读取TextFrame.TextRange.Text
。
使用多个文本框循环:在目标范围内创建(粘贴)文本框后,Word 会说“啊哈!还有另一个文本框!” 并且会尝试循环它,这也不是想要的。因此,问题中的代码已被修改,以添加应复制到数组( shps()
) 中的文本框。一旦确定了所有需要复制的文本框,代码就会循环这个数组,复制每个文本框并将其粘贴到目标范围。
Sub searchTexboxes()
Dim shp As Shape
Dim shps() As Shape
Dim sTemp As String
Dim nrTextboxes As Integer
Dim target As Word.Range
Dim targetPage As Long, i As Long
nrTextboxes = 0
targetPage = 1
Selection.GoTo What:=Word.wdGoToPage, Which:=targetPage
Set target = Selection.Paragraphs(1).Range
For Each shp In ActiveDocument.Shapes
If shp.Type = msoTextBox Then
sTemp = shp.TextFrame.TextRange.Text
sTemp = Left(sTemp, 1)
If sTemp = "." Then
nrTextboxes = nrTextboxes + 1
ReDim Preserve shps(nrTextboxes - 1)
Set shps(nrTextboxes - 1) = shp
End If
End If
Next
For i = LBound(shps) To UBound(shps)
shps(i).Select
Selection.Copy
target.Paste
Next
MsgBox ("Found " & nrTextboxes & " textboxes.")
End Sub
推荐阅读
- c++ - QGridLayout 小部件设置相等大小
- sql - 如果 count(column) 然后在 Oracle 中选择
- c# - 在 Cefsharp.WPF 中,我应该如何对“fi-FI”(芬兰语)语言进行拼写检查?
- python - 我在 Pygame 中收到一个关于字体的表面错误。我该如何解决?
- str-replace - 使用 str_replace 函数回显错误数据
- javascript - 获取“仅对页面组件执行导出的查询”。在 Gatsby 中尝试生成页面时
- flutter - 使用 Flutter 和 Dart 实现多个过滤器
- laravel - 如何编写更改迁移以在 laravel 中添加复合键
- php - 来自 ABAP Web 服务的响应返回多个项目的数组,但返回单个项目的对象
- math - 您如何查找 Coq 证明策略的定义或实现?