复制excel单元格并将其粘贴到特定单词doc

时间:2018-01-16 14:17:46

标签: excel vba excel-vba ms-word copy

我是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

1 个答案:

答案 0 :(得分:0)

InputBox返回String,而不是Object

Dim行更改为:

Dim xRg As String

并将InputBox行更改为:

xRg = InputBox("Please select Cells to copy to word docs:", "Range Selection", ActiveWindow.RangeSelection.Address)
If xRg ="" Then Exit Sub

然后,如果你想把它变成Range对象:

Dim xRange As Object
Set xRange = Range(xRg)

但是,我不建议你这样做。用户输入无效内容的机会太多,您将收到错误。