首页 > 解决方案 > 打开表单后如何在 Word 文档末尾添加子文档?

问题描述

我正在尝试编写一个宏,在打开 Word 文档时将子文档添加到 Word 文档的末尾。有问题的文档中已经有一些文本,所以在运行宏之前,我想将光标移动到文档的末尾。我可以使用代码实现这一点:当我在打开文档Selection.EndKey Unit:=wdStory运行宏时效果很好,但是如果我在使用 Sub 打开文档后立即运行宏:

Private Sub Document_Open()
    Selection.EndKey Unit:=wdStory
    'Add subdocuments based on user input to a form
    '(See edit below)
End Sub

在 ThisDocument 对象中,子文档被添加到文档的开头。这可能是因为光标还没有出现所以Selection还不“存在”。

如何在文档打开时运行宏,但将子文档添加到文档末尾?

我尝试先写一个空格以使光标产生但没有变化...

也欢迎任何有关替代方法的建议。

编辑:ThisDocument中的这段代码:

Private Sub Document_Open()
    CreateWorkbook.Show
End Sub

调用表单 CreateWorkbook,用一个按钮单击子:

Private Sub GenerateButton_Click()
    Dim i As Integer
    Dim rng As Word.Range

    Set rng = ActiveDocument.Content
    rng.Collapse wdCollapseEnd

    'ModulesListBox is a user input box that is a list of paths to the subdocuments
    For i = 0 To ModulesListBox.ListCount - 1
        docpath = ModulesListBox.List(i)
        rng.Subdocuments.AddFromFile docpath
    Next i

End Sub

标签: vbams-word

解决方案


由于该Document_Open事件首先调用用户窗体,因此 Word 确实需要访问文档的机会。以下在我的测试中有效。

'ThisDocument code:
Option Explicit

Private Sub Document_Open()
    Dim f As UserForm1
    Set f = New UserForm1
    Set f.rng = ThisDocument.Content
    f.Show
End Sub

请注意用户表单是如何声明为对象的——用户表单实际上是一个(与 ThisDocument 相同),但 VBA 允许您处理它而无需专门编码为一个类。通常,这有效,但并非总是如此。因此,该对象被声明并分配给它的 UserForm 类的一个新实例

ARange在 UserForm 类中声明为类级别的公共成员。它在 Open 事件中设置为文档的正文。

然后显示用户表单,代码如下。

此时,可以访问 Range 对象,并且可以对其进行实际操作。也就是说,它似乎Subdocuments.AddFromFile依赖于一个选择,就像它依赖于大纲视图一样。这可能是因为该功能可以追溯到旧的 WordBasic 时代,并且从未更改为遵守 VBA 原则。

'Code in the UserForm
Option Explicit

Public rng As Word.Range

Private Sub CommandButton1_Click()
  Me.rng.Collapse 0
  'rng.Text = "Test text"
  ThisDocument.ActiveWindow.View = wdOutlineView
  Me.rng.Select
  Selection.Range.Subdocuments.AddFromFile ("C:\Test\CCRanges.docx")
  Application.ScreenRefresh
End Sub

推荐阅读