Forum Discussion

andryt29's avatar
andryt29
Occasional Contributor
13 years ago

How to get Multiple Excel Instance by Com

Hi  everybody,

I want to get a specific instance of excel to get a specific worbook opened in this instance and save this worbook.



But when I use a TestComplete OleObject or ActiveXObject, I just take an instance of excel that I don't want. (maybe the Active Instance)



I have many excel instances opened with one or many workbook opened in these instances.



I was trying



var oExcel = GetObject("","Excel.Application");

and

var oExcel = Sys.OleObject("Excel.Application")

and

var oExcel = new ActiveXObject("Excel.Application");



but it doesn't work because I get an instance of Excel that I don't want.



Have you  another method to get all excel instances which works with Com Object because I want to save an Workbook with the com method like oWorkBook.SaveAs("C:\myPath..........")?

Can you help me?

Thanks

7 Replies

  • hlalumiere's avatar
    hlalumiere
    Regular Contributor
    If all you need to do is save the files that are opened, you could just enumerate the Excel processes, give each of them focus one at a time, and use the keyboard shortcuts to save the files from a TC script:



    Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

    Set ExcelProcesses = objWMI.ExecQuery("Select * from Win32_Process Where Name = 'EXCEL.EXE'")



    arrProcesses = Sys.FindAllChildren("ProcessName", "EXCEL", 1, True)



    For Each p In arrProcesses

        Set MainWindow = p.Window("XLMAIN", "Microsoft Excel", 1)

        MainWindow.SetFocus

        Sys.Keys "^s"    

    Next
  • hlalumiere's avatar
    hlalumiere
    Regular Contributor
    You cannot. GetObject only returns a reference to the first instance. You could probably do it in .Net, through reflection, and then expose an array of references.



    What you should be doing is only opening the one document you actually need in a new instance.
  • andryt29's avatar
    andryt29
    Occasional Contributor
    Thanks Hugo,

    Do you have a little example of code for me?

    thanks for your help
  • hlalumiere's avatar
    hlalumiere
    Regular Contributor
    Just make sure every Excel is closed, then CreateObject("", "Excel.Application") and work from there on. As long as you keep track of the reference you got when opening the application you can work with multiple instances.
  • andryt29's avatar
    andryt29
    Occasional Contributor
    I can't close the Excel instances because I have to test an Application which generate these Excel Files and I have to save theses excel files by TestComplete

    Do you have an another solution?
  • hlalumiere's avatar
    hlalumiere
    Regular Contributor
    Forget lines one and two in the code above, they are not used I forgot to remove them before posting.