VBA:运行-时间错误“91”(代码在模板中运行但不在 "new from template" 中)

VBA: Run-Time error '91' (Code working in template but not "new from template")

我的代码在 "open" 模板(例如 Template.dotm)中的 运行 时有效,但当我使用 "new from template"(例如 Document1.docx)时无效.

当运行 from "Document1" 错误代码提示:

"Run-time error '91' Object variable or With block variable not set"

调试器亮点:

Selection.MoveDown 单位:=wdLine, 计数:=129

我在 Microsoft Word 对象中的代码/本文档:

Opens Userform1 when making new document from template:

Private Sub Document_New()
    Userform1.Show
End Sub

Userform1 中的代码

EDITED Now "run-time error '438' Object does not supp. property or method."

If CheckBox1 = True it Opens text.docx and pastes its contents in line 129 of this document

    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'

您需要使用文档对象。

Dim myDoc as Document
Set myDoc = Documents.Open(FileName:="C:\Users\Stack\Documents\Text.docx", ReadOnly:=False)

' do some stuff

myDoc.Close

这有效:

Selection.InsertFile 文件名:="file path"