VBA For循环将单元格从excel复制到单词

时间:2013-12-16 23:47:21

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

我正在尝试创建一个excel宏来将单元格从excel复制到word。我需要从excel中的第1页到第1表。

我需要通过循环执行此操作(因为我必须对单元格等执行操作)并且我无法弄清楚如何执行此操作。 我有以下代码:

Sub test()

Dim wdDoc As Object
Dim FileName As String
Dim iRow As Integer
Dim iCol As Integer

'Open Word file
FileName = ActiveWorkbook.Path & "\Template.doc"
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(FileName)



' Loop through columns and rows
For iCol = 1 To 3 ' or however many columns you have
    For iRow = 1 To 2

    With Worksheets("Sheet1").Cells(iRow, iCol)
        ' Copy the cell to the destination
        .Copy
        wdDoc.Selection.Paste
    End With

    Next iRow
Next iCol

End Sub

当我运行时,行 wdDoc.Selection.Paste 会出错:

  

运行时错误'438':对象不支持此属性或方法。

我也知道这不会粘贴到文档的表1中,但是现在它没有任何,所以我想我会先做这个。 我是VBA的新手,但有其他编程经验。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

这应该有效:

wdApp.Selection.Range.Paste

编辑:更完整的示例

Sub test()

Dim wdDoc As Word.Document, wdApp As Word.Application
Dim tbl As Word.Table


Dim FileName As String
Dim iRow As Integer
Dim iCol As Integer


    FileName = "C:\_stuff\Local Files\temp.docx"
    Set wdApp = New Word.Application

    wdApp.Visible = True 'add this to see the Word instance and document

    Set wdDoc = wdApp.Documents.Open(FileName)

    Set tbl = wdDoc.Tables(1)

    ' Loop through columns and rows
    For iRow = 1 To 2
    For iCol = 1 To 3 ' or however many columns you have
        With Worksheets("Sheet1").Cells(iRow, iCol)
            tbl.Rows(iRow).Cells(iCol).Range.Text = .Value
        End With
    Next iCol
    Next iRow


    wdDoc.Close False  ' close doc and save changes
    wdApp.Quit        'close word (will auto-close if no open documents)

End Sub