【发布时间】:2017-08-24 19:44:34
【问题描述】:
我的代码在从“打开”模板(例如 Template.dotm)运行时有效,但在我使用“从模板新建”(例如 Document1.docx)时无效。
从“Document1”运行时出现错误代码提示:
“运行时错误'91'对象变量或未设置块变量”
调试器亮点:
Selection.MoveDown 单位:=wdLine,计数:=129
我在 Microsoft Word 对象/本文档中的代码:
从模板创建新文档时打开 Userform1:
Private Sub Document_New()
Userform1.Show
End Sub
Userform1 中的代码
已编辑现在“运行时错误 '438' 对象不支持属性或方法。”
如果 CheckBox1 = True 则打开 text.docx 并将其内容粘贴到此文档的第 129 行
Private Sub CommandButton1_Click()
Dim Newdocument As Document
Set NewDocument = ThisDocument
Dim myDoc As Document
Set myDoc = Documents.Open(FileName:="C:\Users\Stack\Documents\Text.docx", ReadOnly:=False)
' do some stuff
'Opens text document and pastes it in line 129 of this document
If CheckBox1 = True Then
myDoc.WholeStory
myDoc.Copy
Newdocument.Activate
Selection.MoveDown Unit:=wdLine, Count:=129
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Application.DisplayAlerts = False
myDoc.Close
End If
Unload Me
Exit Sub
End Sub
I probably seem clueless in your eyes, but i am new to VBA and still learning. Debugger now highlights the "mydoc.wholestory" with error '438'
【问题讨论】:
-
不要使用
Selection。根据@braX,定义一个对象并使用myDoc.WholeStory。 ... 还为 ThisDocument 定义一个对象,在 myDoc 之前定义它。 ...也不要使用复制/粘贴来插入文本 -
问题是我不知道如何定义这个文档,因为它在从模板创建时还没有保存。我已经用你的和@brax cmets 编辑了我的原始帖子。 :)
标签: vba templates runtime-error selection