How to get data from an already opened excel workbook with a Word macro?

杀马特。学长 韩版系。学妹 提交于 2019-11-30 21:09:20

问题


I am currently struggling with a vba macro, could you help me please? I would be very thankful to anyone who can help me on this.

I want to access data of an Excel opened workbook from a Word Document macro. For some reasons I need to take data from the Excel workbook which is already opened on my user session and not to reopen it in the background by using its path.

Here is the current bit of macro I want to transform so that I use the “GUI.xls” which is already opened. The window’s name is “Microsoft Excel – GUI.xls [Compatibility Mode]” I hope I explained well enough my problem, I didn’t find this topic elsewhere, sorry if it already exists.

If it is possible I would like that the AppExcel Object is directly linked to the opened Workbook. The problem is that I try to access the Workbook from Word.

Thank you very much for your help,

Simon

Set AppExcel = CreateObject("Excel.Application")
AppExcel.Workbooks.Open SourcePath1 & "" & "\GUI.xls"

    Data_Name = AppExcel.Worksheets("Output").Cells(RowNum, 2).value
    Data_Ending = AppExcel.Worksheets("Output").Cells(RowNum, 3).value

Dim WordFileName As String
WordFileName = Data_Name & Data_Ending

    Call candp(SourcePath, WordFileName, TargetName)

AppExcel.Activeworkbook.Close savechanges:=False
AppExcel.Quit
Set AppExcel = Nothing

回答1:


Try to use GetObject:

Dim WordFileName As String
Dim exWb As Object
Dim AppExcel As Object

'try to get file if it's already open
On Error Resume Next
Set exWb = GetObject(SourcePath1 & "\GUI.xls")
On Error GoTo 0

'if it's not already opened - open it
If exWb Is Nothing Then
    Set AppExcel = CreateObject("Excel.Application")
    Set exWb = AppExcel.Workbooks.Open(SourcePath1 & "\GUI.xls")
End If

With exWb.Worksheets("Output")
    Data_Name = .Cells(RowNum, 2).Value
    Data_Ending = .Cells(RowNum, 3).Value
End With

WordFileName = Data_Name & Data_Ending

Call candp(SourcePath, WordFileName, TargetName)

exWb.Close savechanges:=False
Set exWb = Nothing

If Not AppExcel Is Nothing Then AppExcel.Quit
Set AppExcel = Nothing


来源:https://stackoverflow.com/questions/22150619/how-to-get-data-from-an-already-opened-excel-workbook-with-a-word-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!