vba - 打开表单后如何在 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
解决方案
由于该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
推荐阅读
- javascript - 如何在不刷新浏览器的情况下获取更改?
- ios - GraphQL 架构文件应包含有效的 GraphQL 自省查询结果
- django - 向 django 发出 axios 请求
- reactjs - 创建 React 应用程序时出现 NPM 和 Yarn Registry 问题
- jenkins - Jenkins 失败的屏幕截图
- ms-access - 用于更改组合框选择的 Win32 API 调用
- asp.net-web-api2 - 在 Web API 中提供 VB.net DLL 参考
- asynchronous - Netty Http 客户端分析。如何计算服务器响应时间?
- upgrade - 我正在尝试将 Grails 2.4 升级到 3.3.6 并且无法更改环境:从开发到测试。有人能帮我吗?
- docker - Windows 上的 Docker 构建未能建立新连接 Errno 11001 getaddrinfo failed