2017-08-03 15 views
1

我的代码在从“打开”模板(例如Template.dotm)运行时起作用,但当我使用“new从模板“(例如Document1.docx)。VBA:运行时错误'91'(代码在模板中工作,但不是“从模板中新建”)

当从 “文档1” 的错误代码运行提示

“运行时错误 '91' 对象变量或With块变量未设置”

调试器亮点:

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

我在Microsoft Word Obejcts /文档代码:

从模板制作的新文档时打开Userform1:在Userform1

Private Sub Document_New() 
    Userform1.Show 
End Sub 

代码

EDITED现在“运行时错误'438'对象不支持。属性或方法。”

如果CheckBox1 =真它打开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' 
+0

不使用'Selection'。根据@braX,定义一个对象并使用'myDoc.WholeStory'。 ...也为ThisDocument定义一个对象,在myDoc之前定义它。 ...也不要使用复制/粘贴插入文本 – jsotola

+0

问题是,我不知道如何定义此文档,因为它从模板创建时尚未保存。我已经编辑了您的原始文章并考虑了@brax评论。 :) – OverflowNoob

回答

0

这工作:

Selection.InsertFile FileName:=“file path”

0

您需要使用一个文档对象。

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

' do some stuff 

myDoc.Close 
+0

感谢您抽出宝贵时间帮助我:)我已经发布了我尝试将对象应用到顶端! – OverflowNoob

+0

我无法让它为模板和模板中的新模板工作:( – OverflowNoob