我需要将表从Excel复制/粘贴到特定行。我已经编写了代码,它在我使用的Excel和Word 2016中运行良好,但是当我尝试在其他版本(2013,2010,2007)中运行时它根本不起作用。所以我尝试使用后期绑定,但它在.selection
中抛出了Bad Parameters错误
如何删除错误的参数?谢谢,
这是代码:
Sub Movetable ()
'Name of the existing Word document
Const stWordDocument As String = "Test.docx"
'Word objects.
Dim wdApp As Object
Dim wdDoc As Object
Dim wdRange As Object
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim xlRange As Excel.Range
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Worksheets("RJ").Select
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Set xlRange = Range("A4:D" & LastRow)
xlRange.Select
xlRange.Copy
'Instantiate Word and open the "Test" document.
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)
wdDoc.Application.Selection.Find.Execute "Table 1. Summary", MatchCase:=True
wdApp.Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdMove
wdApp.Selection.PasteExcelTable False, False, False
wdDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
wdApp.Quit
'Null out the variables.
Set wdRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
很可能,原因是您已为2016版本设置了Microsoft Word库的参考。当您在早期版本中打开并运行项目时,该引用不会更改为该版本的Microsoft Word库。这是预期的行为。
要解决问题,您也可以
MatchCase:=
,Unit
,Count
,Extend
。另外,不要使用Word枚举:wdLine
,wdMove
,wdAutoFitWindow
-这些都具有数字等价物,而是使用它们。这称为“后期绑定”,它使您的项目独立于Word的版本。然后,您可以完全删除对Microsoft Word库的引用。
为了找出数字等价物,您可以在VBA对象浏览器中查找枚举(VBA编辑器中的F2),在Word VBA帮助中查找它们或在VBA编辑器立即窗口(Ctrl + G)中查询它们像这样的语法:?wdLine
然后按Enter执行。