VBA - 从Word运行宏以将值粘贴到Excel中

时间:2017-06-06 22:09:57

标签: excel vba ms-word

我对VBA比较新,我不知道为什么我不能从Word粘贴到Excel中。以下宏最终将值粘贴到Word中,即使我认为我正在激活Excel文档 该宏旨在从Word运行;然后,需要将来自各种FormField的值粘贴到现有Excel文件的单元格中。 我搜索了一个类似的问题,虽然返回的内容似乎是我所经历的变化,但我无法修改这些答案。 任何帮助将不胜感激。

Sub Transfer()

Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook

Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True 
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook

WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste

End Sub

2 个答案:

答案 0 :(得分:0)

您的Selection指的是当前的应用程序。要引用Excel应用程序,您需要使用ED.Selection。但是,无论如何依赖ActivateSelect是个坏主意。

我建议您将代码更改为:

Sub Transfer()

    Dim WD As Document
    Dim ED As Excel.Application
    Dim EDS As Excel.Workbook

    Set WD = ActiveDocument
    Set ED = CreateObject("excel.application")
    ED.Visible = True 
    'Avoid "Activate"
    Set EDS = ED.Workbooks.Open(FileName:= _
             "C:\Users\Documents\AppealData.xlsx")

    WD.FormFields("AppNum").Copy
    'Avoid "Activate" and "Select" and "Selection"
    '"Paste" is a worksheet Method, use "PasteSpecial" for a Range
    'Use "xlPasteValues" to avoid formatting issues
    EDS.Sheets("Sheet1").Range("A1").PasteSpecial Excel.xlPasteValues
End Sub

答案 1 :(得分:0)

这里应该适合你。

Sub Transfer()
   Dim oExcel As Excel.Application
   Dim oWB As Workbook

   Set oExcel = New Excel.Application
   Set oWB = oExcel.Workbooks.Open("C:\Users\Documents\AppealData.xlsx")

   oExcel.Visible = True

   Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1).Value = _ 
      CStr(Documents("Document1").FormFields("AppNum").Result)
End Sub