[英]VBA For loop to copy cells from excel to word
I'm trying to create an excel macro to copy cells from excel to word. 我正在尝试创建一个Excel宏,以将单元格从excel复制到word。 I need to take it from sheet 1 in excel to table 1 in word. 我需要将其从excel的工作表1中提取到单词表1中。
I need to do this via a loop (as I have to perform operations on the cells etc.) and I can't work out how to do it. 我需要通过循环执行此操作(因为我必须在单元格上执行操作等),但我不知道如何执行此操作。 I have the following code: 我有以下代码:
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
When I run this though, the line wdDoc.Selection.Paste gives the error: 但是,当我运行此命令时,行wdDoc.Selection.Paste给出了错误:
Run-time error '438': Object does not support this property or method. 运行时错误“ 438”:对象不支持此属性或方法。
I'm also aware that this doesn't paste into table 1 of the document, but right now it doesn't do anything , so I thought I'd work on that first. 我也知道,这并不粘贴到文档中的表1中,但现在它没有做任何事情 ,所以我想我会在有效的第一次。 I'm new to VBA but have other programming experience. 我是VBA的新手,但有其他编程经验。 Can someone please help me? 有人可以帮帮我吗?
This should work: 这应该工作:
wdApp.Selection.Range.Paste
EDIT : more complete example 编辑 :更完整的例子
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.