嗨,当我尝试将表格从Excel添加到Word文档时,出现此错误450。我从单词宏记录器复制了代码。还尝试过使用https://docs.microsoft.com/en-us/office/vba/api/word.tables.add此处的语法,例如Tables.Add(Selection.Range,3,5)并将其设置为表对象,但仍然没有运气。
Sub ExcelToWord()
'
' Select data in excel and copy to GIR
'
'
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim wb As Workbook
Dim ws As Worksheet
Dim wdApp As Word.Application
Dim GIR As Word.Document
Dim GIRName As String
Dim GEOL As String
Dim Tbl As Long
Dim NewTbl As Word.Table
Set wdApp = New Word.Application '<<< Create a Word application object
wdApp.Visible = True '<<<< Open word so you can see any errors
GIRName = Application.GetOpenFilename(Title:="Please choose GIR to open", _
FileFilter:="Word Files *.docm* (*.docm*),")
Set GIR = wdApp.Documents.Open(GIRName) '<< call Documents.Open on the word app
'Loop through excel workbook to copy data
Set wb = ThisWorkbook
Set ws = ActiveSheet
For Each ws In wb.Worksheets
If UCase(ws.Name) <> "TEMPLATE" And ws.Visible = True Then
ws.Name = Replace(ws.Name, "(Blank)", "NoGEOLCode")
ws.Activate
GEOL = Range("C9").Value
Tbl = 1
Range("A14").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste each worksheet's data into word as new heading
wdApp.Selection.GoTo What:=wdGoToHeading, Which:=wdGoToFirst, Count:=4, Name:=""
wdApp.Selection.EndKey Unit:=wdLine
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 2")
wdApp.Selection.TypeText Text:=GEOL
wdApp.Selection.TypeParagraph
Set NewTbl = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=53, NumColumns _
:=7, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitWindow)
With wdApp.Selection.Tables(Tbl)
If .Style <> "Table1" Then
.Style = "Table1"
End If
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
.ApplyStyleRowBands = True
.ApplyStyleColumnBands = False
End With
wdApp.Selection.PasteAndFormat (wdFormatPlainText)
Tbl = Tbl + 1
wdApp.Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst, Count:=6, Name:=""
wdApp.Selection.MoveUp Unit:=wdLine, Count:=1
wdApp.Selection.TypeParagraph
End If
Next
GIR.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub