简体   繁体   中英

copy excel cell and paste it to specific word doc

I'm new to VBA and I need to copy one cell (that contains Data) from excel to a specific (not from a template) word document. the full path of the specific file will be in a cell next to the targeted cell - offset(0,1). All of that obviously in a loop because I have a big list and a lot of files.

this is my code (the code is made of some part I picked up while searching) - but I get an

object error

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

InputBox returns a String , not an Object .

Change the Dim line to this:

Dim xRg As String

and change the InputBox lines to this:

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

Then if you want to turn it into a Range object:

Dim xRange As Object
Set xRange = Range(xRg)

However, I do not recommend doing what you are doing this way. There are too many chances the user will enter something invalid and you will get errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM