[英]VBA - Run Macro from Word to paste values into Excel
I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word. 我对VBA相对较新,对为什么无法从Word粘贴到Excel感到困惑。 The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document. 下面的宏最终将值粘贴到Word中,即使我认为我正在激活Excel文档。
The macro is meant to be run from Word; 该宏应从Word运行; values from various FormFields then need to be pasted into cells in an existing Excel file. 然后需要将来自各种FormField的值粘贴到现有Excel文件中的单元格中。 I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this. 我搜索了一个类似的问题,尽管返回的内容似乎是我所遇到的变化,并且我无法修改这些答案。 Any help would be appreciated. 任何帮助,将不胜感激。
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
Your Selection
is referring to the current application. 您的Selection
是指当前应用程序。 To refer to the Excel application you need to use ED.Selection
. 要引用Excel应用程序,您需要使用ED.Selection
。 But it is a bad idea to rely on Activate
and Select
anyway. 但是无论如何都要依靠Activate
和Select
是一个坏主意。
I suggest you change your code to: 我建议您将代码更改为:
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
This here should work for you. 这在这里应该为您工作。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.