【问题标题】:VBA: Run-Time error '91' (Code working in template but not "new from template")VBA:运行时错误'91'(代码在模板中工作,但不是“来自模板的新代码”)
【发布时间】: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


【解决方案1】:

这行得通:

Selection.InsertFile FileName:="文件路径"

【讨论】:

    【解决方案2】:

    您需要使用文档对象。

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

    【讨论】:

    • 感谢您抽出宝贵时间来帮助我 :) 我已经发布了我在顶部应用对象的尝试!
    • 我现在无法让它同时适用于打开的模板和来自模板的新模板 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多