【发布时间】:2018-06-25 06:49:00
【问题描述】:
我是 VBA 新手,我需要将一个单元格(包含数据)从 excel 复制到 特定(不是来自模板)word 文档。特定文件的完整路径将位于目标单元格旁边的单元格中 - 偏移量(0,1)。所有这些显然都在一个循环中,因为我有一个很大的列表和很多文件。
这是我的代码(代码由我在搜索时拾取的部分组成) - 但我得到了一个
对象错误
Sub OpenWordFile()
Dim oWord As Object
Dim xRg As Object
Dim xCell As Range
Dim xVal As Range
Dim Workbook As Workbook
Dim FileName As Variant
'Word Object
Set oWord = CreateObject(Class:="Word.Application")
oWord.Visible = True
'Open Word Document (need to be multiple files in a loop)
'oWord.documents.Open FileName:="C:\Users\tamirre\Desktop\New folder\135-185844.doc" ' OPEN AN EXISTING FILE.
'Set oWord = Nothing
'Activating Excel to copy Cells
ThisWorkbook.Worksheets("Sheet1").Activate
Set xRg = Application.InputBox("Please select Cells to copy to word docs:", ActiveWindow.RangeSelection.Address, , , , , 8)
If xRg Is Nothing Then Exit Sub
For Each xCell In xRg
xVal = xCell.Value
Set FileName = xVal.Offset(0, 1) 'Cell Must Contain name and full path of the doc file
xVal.Copy
oWord.documents.Open FileName:="FileName"
Selection.EndKey Unit:=wdStory
Selection.TypeParagraph
Selection.PasteExcelTable True, False, False
Next
End Sub
【问题讨论】:
-
(a) 您可能需要将
Selection更改为oWord.Selection,否则它会认为它指的是Excel 的Selection对象。 (b) 除非您引用了 Excel 项目中包含的 Word 对象库,否则wdStory将默认为零 - 您需要将其设置为6(c) 如果xVal则xVal = xCell.Value没有意义是一个Range对象。我怀疑你只是想说Set xVal = xCell,但我不确定。 -
(d) 您的
InputBox将HelpContextID设置为8。您要么需要添加额外的,,要么使用Type:=8