我'm trying to write a macro that adds subdocuments to the end of a Word document when the Word document is opened. The document in question already has some text in it, so before running the macro I' d喜欢将光标移动到文档的末尾 . 我可以使用代码实现这一点: 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
还没有't '存在 .
如何在文档打开时运行我的宏,但是将子文档添加到文档的末尾?
我先尝试写出一个空格,使光标产生但没有变化......
对替代方法的任何建议也欢迎 .
编辑: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
1 回答
由于
Document_Open
事件首先调用UserForm,因此Word确实需要有机会访问该文档 . 以下工作在我的测试中 .注意用户表单是如何声明为对象的 - UserForm实际上是一个类(与ThisDocument相同),但是VBA允许您处理它而无需专门编写类 . 通常,这有效,但并非总是如此 . 因此声明了对象,并为其分配了一个UserForm类的新实例 .
Range
在UserForm类中声明为类级别的公共成员 . 它在Open事件中设置为文档的正文 .然后显示用户表单,代码如下 .
此时,可以访问Range对象,并且可以进行实际的工作 . 也就是说,似乎
Subdocuments.AddFromFile
依赖于一个选择,就像它依赖于大纲视图一样 . 这可能是因为功能可以追溯到旧的WordBasic日期,并且从未更改为遵守VBA原则 .