首页 > 解决方案 > 如何以编程方式将 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

标签: vbams-word

解决方案


以下代码适用于我。

真正做到这一点的唯一方法(除了从头开始重新创建文本框)是复制/粘贴。这将贯穿所有格式。

这种方法的关键方面:

设置目标页面:由于 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

推荐阅读