Shapes.AddTextbox 在 Word 文档中放在第一页之后的错误位置

Shapes.AddTextbox being placed at wrong position in Word doc after the first page

我在尝试从 Excel 文件向 Word 文档添加文本框时遇到了这个奇怪的问题。文本框被放置在所有包含 table 的页面中的循环中。当我 运行 代码时,第一个文本框放置正确,但是当我递增以转到下一页(那里有 table)时,文本框放置在错误的位置。

我注意到,当我删除 table 元素时,代码工作正常并且所有文本框都正确放置,但是当我添加回 table 时,第一页显示正常,但后续页面文本框放置不正确。下面是一个例子:

这是我的代码片段:

Public Sub test9()
Dim objWord As Object
Dim objDoc As Object
Dim box As Object

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\user\Downloads\Test2.docx")
objWord.Visible = True

For i = 1 To 10
        objWord.Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i
        Set doc = objWord.ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20)
        doc.TextFrame.TextRange.InsertAfter "Test Box" & i
Next i
End Sub

要重现错误,您可以在多个页面中创建 tables,如果您 运行,您将看到如图所示的输出。

我不确定是什么原因造成的,或者如果我遗漏了什么,请指出。

这对我有用 - 获取所需页面的范围 - 然后将文本框形状锚定到它。

我在 Word 中对其进行了测试 - 您必须进行修改以匹配您的对象声明

Sub test()

    Dim i As Integer
    Dim objTextBox As Object ' TextBox Shape
    Dim objRge As Object ' Word Object Range

    For i = 1 To ActiveDocument.ComputeStatistics(wdStatisticPages)
        Set objRge = ActiveDocument.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i)
        Set objRge = objRge.GoTo(What:=wdGoToBookmark, Name:="\page")

        ' next you specify the page range as your textbox anchor parameter
        Set objTextBox = ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20, Anchor:=objRge)
        objTextBox.TextFrame.TextRange.InsertAfter "Test Box" & i
    Next i
End Sub

如果您 运行 来自 Excel 并且没有对 Word 的引用,则需要预定义 Word 常量 - 试试这个

Option Explicit

Const TestDoc As String = "C:\Users\<yourusername>\Documents\Test2.docx"


Public Sub TestFromExcel()

    Dim objWord As Object
    Dim objDoc As Object
    
    Dim box As Object
    
    ' Define Word constants in Excel if you don't have a reference to WORD
    Const wdGoToAbsolute    As Long = 1
    Const wdStatisticPages  As Long = 2
    Const wdGoToPage        As Long = 1
    Const wdGoToBookmark    As Long = -1
    
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open(TestDoc)
    objWord.Visible = True

    Dim i As Integer
    Dim objTextBox As Object ' TextBox Shape
    Dim objRge As Object ' Word Object Range

    For i = 1 To objDoc.ComputeStatistics(wdStatisticPages)
        Set objRge = objDoc.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i)
        Set objRge = objRge.GoTo(What:=wdGoToBookmark, Name:="\page")
        Set box = objDoc.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20, Anchor:=objRge)
        box.TextFrame.TextRange.InsertAfter "Test Box" & i
    Next i

End Sub