错误:尚未定义对象

时间:2017-11-21 01:51:51

标签: excel vba excel-vba

我只是引用了一些示例代码,希望将Excel表格移动到新的word文档中。

但是,它至少包含一个错误。

Set tbl = ThisWorkbook.Worksheets(Sheet9.Name).ListObjects("Table1").Range 
  

错误:此处需要对象。

链接: https://www.thespreadsheetguru.com/blog/2014/5/22/copy-paste-an-excel-table-into-microsoft-word-with-vba

完整代码:

Sub ExcelRangeToWord()

    'PURPOSE: Copy/Paste An Excel Table Into a New Word Document
    'NOTE: Must have Word Object Library Active in Order to Run _
      (VBE > Tools > References > Microsoft Word 12.0 Object Library)
    'SOURCE: www.TheSpreadsheetGuru.com

    Dim tbl As Excel.Range
    Dim WordApp As Word.Application
    Dim myDoc As Word.Document
    Dim WordTable As Word.Table

    'Optimize Code
      Application.ScreenUpdating = False
      Application.EnableEvents = False

    'Copy Range from Excel
      Set tbl = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects("Table1").Range

    'Create an Instance of MS Word
      On Error Resume Next

        'Is MS Word already opened?
          Set WordApp = GetObject(class:="Word.Application")

        'Clear the error between errors
          Err.Clear

        'If MS Word is not already open then open MS Word
          If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

        'Handle if the Word Application is not found
          If Err.Number = 429 Then
            MsgBox "Microsoft Word could not be found, aborting."
            GoTo EndRoutine
          End If

      On Error GoTo 0

    'Make MS Word Visible and Active
      WordApp.Visible = True
      WordApp.Activate

    'Create a New Document
      Set myDoc = WordApp.Documents.Add

    'Copy Excel Table Range
      tbl.Copy

    'Paste Table into MS Word
      myDoc.Paragraphs(1).Range.PasteExcelTable _
        LinkedToExcel:=False, _
        WordFormatting:=False, _
        RTF:=False

    'Autofit Table so it fits inside Word Document
      Set WordTable = myDoc.Tables(1)
      WordTable.AutoFitBehavior (wdAutoFitWindow)

    EndRoutine:
    'Optimize Code
      Application.ScreenUpdating = True
      Application.EnableEvents = True

    'Clear The Clipboard
      Application.CutCopyMode = False

    End Sub

1 个答案:

答案 0 :(得分:0)

根据您在评论中提供的信息,您似乎在工作表中实际上没有表格(这就是ListObjects("Table1")没有返回对象的原因)而您实际上只是想要转移Range

如果是这样,请将行设置tbl替换为:

Set tbl = ThisWorkbook.Worksheets("whatever_sheet_name_you_are_using")‌​.Range("A1:E10")