VBA For循环将单元格从excel复制到word
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20623301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA For loop to copy cells from excel to word
提问by Sam Rogers
I'm trying to create an excel macro to copy cells from excel to word. I need to take it from sheet 1 in excel to table 1 in word.
我正在尝试创建一个 excel 宏来将单元格从 excel 复制到 word。我需要将它从 excel 中的表 1 中取出到 word 中的表 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.Pastegives 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. I'm new to VBA but have other programming experience. Can someone please help me?
我也知道这不会粘贴到文档的表 1 中,但现在它没有做任何事情,所以我想我会先解决这个问题。我是 VBA 新手,但有其他编程经验。有人可以帮帮我吗?
回答by Tim Williams
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