【发布时间】:2017-11-21 01:51:51
【问题描述】:
我只是参考一些示例代码,希望将 Excel 表格移动到新的 word 文档中。
但是,它至少包含一个错误。
Set tbl = ThisWorkbook.Worksheets(Sheet9.Name).ListObjects("Table1").Range
错误:此处需要对象。
完整代码:
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
【问题讨论】:
-
我最好的猜测是您将工作表的 name 与工作表的 codename 混淆了。在上面,您使用代号来检索名称。 Table1 位于哪个工作表(名称)上,与该工作表名称相关联的 VBE 的 VBA 项目窗口 (Ctrl+R) 中的代号是什么?
-
如果您的宏工作簿确实有一张带有
Sheet1的CodeName的工作表(或根据错误的Sheet9?!?)包含一个名为"Table1",然后ThisWorkbook.Worksheets(Sheet1.Name).可以缩短为Sheet1. -
@YowE3K `你是什么意思包含一个表调用
table1?` -
您正在尝试使用
....ListObjects("Table1"),它(AFAIK)指的是名为“Table1”的表格,即如果您在工作表上插入表格,默认表格将被调用。你的工作表上有表格吗?如果没有,那可能就是您无法访问它的原因。 -
@YowE3K `指的是名为“Table1”的表,`这意味着名为“table1”的工作表?我有 !现在提示
array list out of bound