【问题标题】:How do I add subdocments to the end of a Word Document after opening a Form?打开表单后如何在 Word 文档末尾添加子文档?
【发布时间】:2018-08-01 13:51:14
【问题描述】:

我正在尝试编写一个宏,以便在打开 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

【问题讨论】:

  • 尝试在该行之前添加Selection.Wholestory
  • @dwirony 不幸的是没有变化-谢谢你的建议。

标签: vba ms-word


【解决方案1】:

由于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 类的 新实例

Range 在 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

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多