将指定excel文件中的数据复制到word文档

时间:2016-05-31 12:05:54

标签: excel vba ms-word

有人可以请求帮助 - 我正在使用此代码将数据从excel复制到word:

Sub CreateRapport()

Dim wdApp As Object
Dim wd As Object

On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
    Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set wd = wdApp.Documents.Add

wdApp.Visible = True

Sheets("Rapport").Activate
Set Rng = ThisWorkbook.ActiveSheet.Range("A1:E76")

Rng.Copy

With wd.Range
    .Collapse Direction:=0                  'Slutet av dokumentet
    .InsertParagraphAfter                   'Lägg till rad
    .Collapse Direction:=0                  'Slutet av dokumentet
    .PasteSpecial False, False, True        'Pasta som Enhanced Metafile
    End With
    End Sub

我需要在代码中修改什么来复制指定Excel文件中的数据,例如&#34; C:\ Book.xlsx&#34; (不是ThisWorkbook)?我是VBA的新手,所以任何提示都会有所帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

Sub CreateRapport()

Dim wdApp As Object
Dim wd As Object

On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
    Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set wd = wdApp.Documents.Add

wdApp.Visible = True

Dim wBK as WorkBook
Set wBK = Workbooks.Open("C:\\test.xlsx")

wBK.Sheets("Rapport").Activate
Set Rng = wBK.ActiveSheet.Range("A1:E76")

Rng.Copy

With wd.Range
    .Collapse Direction:=0                  'Slutet av dokumentet
    .InsertParagraphAfter                   'Lägg till rad
    .Collapse Direction:=0                  'Slutet av dokumentet
    .PasteSpecial False, False, True        'Pasta som Enhanced Metafile
End With
End Sub