11

This post 4594 shows how to open a existent Excel file with Mathematica. And this 6686886 shows how to do what I need, but in C#. This 12282310 is another related one.

How can I connect to a spreadsheet that is already open?

Murta
  • 26,275
  • 6
  • 76
  • 166

1 Answers1

12

Using SE as my rubber duck to organize ideas worked just nice. I found the answer in NETLinkUserGuide.

To get current Excel session use GetActiveCOMObject instead of CreateCOMObject. Here is a code example.

Needs["NETLink`"]
InstallNET[]
excel=GetActiveCOMObject["Excel.Application"]
workbook=excel@Workbooks["MySpreadsheet.xlsx"];
worksheet=workbook@Worksheets["Sheet1"];
worksheet@Range["A1"]@Value="1, 2, 3 testing"

To get your active workbook use:

With[{$name=excel@ActiveWorkbook@Name},
    workbook=excel@Workbooks[$name]
]

instead of:

workbook=excel@Workbooks["MySpreadsheet.xlsx"];

PS: any tip to replace code injection using With is welcome.

Murta
  • 26,275
  • 6
  • 76
  • 166
  • Humanity needs more Ducks (plus 1 Quacker). –  Apr 18 '15 at 05:46
  • +1 Seems promising! Its a pity that all this isn't more explored by WR. After their ?acquisition? of the "link for excel", I was hoping for its inclusion in standard Mathematica... and, who knows, allowing for Enterprise CDF to work as an Excel computational kernel on previously signed user functions. With the Enterprise, I always have the feeling that I'm paying too much for too little... – P. Fonseca Apr 18 '15 at 09:48