使用 Excel 和 Word 2013 和 Windows 8:
本质上,我有一个 excel 模板,我想将其更新为 word 模板。我在 Word 中有大约 20 个表格,这些表格都是预先格式化的,我想从 excel 中的相应列更新这些列,但使用 vba 和 word 表格非常困难。
尝试复制 Excel 中的某个范围,通过在两个书签之间进行选择来选择 Word 中的相应范围,然后粘贴数据。我收到运行时错误“438”:对象不支持此属性或方法
我意识到这可能不是完成这项任务的理想策略,因此如果您能用代码提出更好的策略,我将不胜感激。
Sub PopulateColumninWord()
Dim wdApp As Word.Application
Dim wdDoc As Document
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
Set rngStart = ActiveDocument.Bookmarks("Start").Range
Set rngEnd = ActiveDocument.Bookmarks("End").Range
ActiveSheet.Range("C2:C19").Select
Selection.Copy
With wdDoc
.Range(rngStart.Start, rngEnd.End).Select
.PasteAndFormat
End With
Set wdApp = Nothing
Set wdDoc = Nothing
End Sub
答案1
本示例将单元格A1:A2
从 Excel 复制到 Word
使用书签
Sub PopulateColumninWord()
Dim wdApp As Object
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
'Read in position of two bookmarks named START and END
Set rngStart = wdDoc.Bookmarks("Start").Range
Set rngEnd = wdDoc.Bookmarks("End").Range
'Copy range from Excel to Word
ThisWorkbook.Sheets(1).Range("A1:A2").Copy
wdDoc.Range(rngStart.End + 1, rngEnd.Start - 1).PasteAndFormat (22)
Set wdApp = Nothing
Set wdDoc = Nothing
End Sub
在 Word 中使用表格
Sub PopulateColumninWord()
Dim wdApp As Object
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
'Copy range from Excel to Word
ThisWorkbook.Sheets(1).Range("A1:A2").Copy
wdDoc.Range(wdDoc.Tables(1).Cell(1, 1).Range.Start, _
wdDoc.Tables(1).Cell(2, 1).Range.End).PasteAndFormat (22)
'Copy single cell from Excel to Word
ThisWorkbook.Sheets(1).Cells(1, 2).Copy
wdDoc.Tables(1).Cell(1, 2).Range.PasteAndFormat (22)
Set wdApp = Nothing
Set wdDoc = Nothing
End Sub