PDA

View Full Version : Using VBA/VB.net to access an open instance of Excel



mp4-4
09-02-2015, 12:14 PM
I wonder if there is any way for a VBA Subroutine (running in a Workbook 'A') to access an already open instance of Excel containing a Workbook 'B'.

In detail, here is my Problem Statement: I have a Workbook 'A' that is opened, and has a Sub that detects to see if Workbook 'B' is open and running. It then copies and pastes values to it. If Workbook 'B is not open and running, then Workbook 'A' opens Workbook 'B'. However, if Workbook 'B' found, there is no need to open it again.

I think the following methods may work, please let me know what you think about this:

Method 1:
Workbook 'A' looks at open processes
If Excel process found, get all names of workbooks they contain
If Workbook 'B' is a name found, then get the process ID
Use this Process ID to refer and create an object for it
Refer to Workbook 'B' from Workbook 'A' thru this object

But I have been unable to track open instances of Excel and their Process IDs.

Method 2:
When Workbook 'B' opens, it writes down its Process ID in a .txt file on disk
Workbook 'A' reads .txt to detect if Workbook 'B' is open
Process ID is obtained thru this .txt file
Use this Process ID to refer and create an object for it
Refer to Workbook 'B' from Workbook 'A' thru this object


Any way to accomplish this complicated maneuver thru VBA (or even VB.net) ?

Aflatoon
09-03-2015, 07:24 AM
Use GetObject and pass the full file path to it. If the workbook is open, you'll get a reference to it; if not, it will be opened (invisibly).