如何使用VB代码将MS Excel中的单元格中的值复制到MS Word文件中的字段?

时间:2009-07-09 15:43:34

标签: excel ms-word word-vba

我需要在ms word 2003中有一个vb代码,它复制excel文件中的特定单元格并将其粘贴到word(字段)中。以下是我所做的,导致错误。

Sub cmdGetNumber()
Dim XL As Object
Dim WBEx As Object
Dim ExelWS As Object
Dim appwd As Object
Dim wdApp As Word.Application

''''

'On Error GoTo OLE_ERROR
Set XL = CreateObject("Excel.Application")
Set wdApp = CreateObject("Word.Application")

'Open Excel document
Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
Set ExelWS = WBEx.Worksheets("Sheet1")
XL.Visible = True
'appwd.Visible = True

ExelWS.Range("c2").Select
'Selection.Copy

'wdApp.Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteMetafilePicture
'wdApp.Documents.Save
Set wdApp = Nothing
Set ExelWS = Nothing
Set WBEx = Nothing

End Sub

1 个答案:

答案 0 :(得分:2)

由于此宏在Word中,因此您无需显式打开单词实例。您可以Documents.Add添加新文档,或Documents.Open打开现有文档。

试试这个:

Sub cmdGetNumber()
    Dim XL As Object
    Dim WBEx As Object
    Dim ExelWS As Object
    Dim wdDoc As Word.Document

    'On Error GoTo OLE_ERROR
    Set XL = CreateObject("Excel.Application")

    'Open Excel document
    Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
    Set ExelWS = WBEx.Worksheets("Sheet1")
    'XL.Visible = True
    ExelWS.Range("C2").Copy

    Set wdDoc = Documents.Add
    wdDoc.Activate
    wdDoc.Select
    Selection.Paste

    WBEx.Close
    XL.Quit
    Set WBEx = Nothing
    Set ExelWS = Nothing
    Set XL = Nothing
End Sub

上面的代码将打开你的excel文件,复制单元格C2,然后打开一个新的word文档,并将其粘贴到那里。

我看到你在问题中提到了(filed)。您的意思是Field还是File?如果是Field,那么您可能希望将Selection.Paste替换为相关字段名称