4

I am trying to use F# to automate some Excel tasks. I actually got two issues: 1. If I open a workbook using an Excel.Application instance, I would miss all the add-ins that would have been automatically loaded if I had just opened the workbook in Excel. So I try to open the workbook in Excel first, with all add-ins loaded, and then hand the instance to F#. Then I got the second issue: 2. The Marshal.GetActiveObject("Excel.Application") actually open a new instance, instead of getting the existing instance. The code is below:

#r "Microsoft.Office.Interop.Excel"
#r "office"

open Microsoft.Office.Interop
open System
open System.Runtime.InteropServices

let app = Marshal.GetActiveObject("Excel.Application")
let app1 = app :?> Excel.Application

let wb = app1.ActiveWorkbook

let visible = app1.Visible

let n = app1.Workbooks.Count

and the output is:

val app : obj

val app1 : Excel.Application

val wb : Excel.Workbook = null

val visible : bool = false

val n : int = 0

But I am very sure I have an Excel instance running and it is visible. Thanks!

Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68
xiphoid
  • 73
  • 4
  • 1
    Have you seen [Excel interop loading XLLs and DLLs](http://stackoverflow.com/questions/13567512/excel-interop-loading-xlls-and-dlls) I do not have Excel so I can't test it for F#. – Guy Coder Mar 24 '16 at 01:44
  • @GuyCoder: Thank you very much for pointing to that post! It seems to be able to solve my problem, but needs some time to digest. I actually do not mind to do some manual operation so I'll prefer my second approach if it could work. It just looks unreasonable why it does not work. – xiphoid Mar 24 '16 at 01:55

1 Answers1

1

I have double checked my code and this is the way to use Excel from F# script (use Excel-DNA for other cases). However, very often (especially when using add-ins) Excel does not close properly and some semi-dead Excel processes hang in the task manager until they are manually killed. Probably you are getting a wrong process, not the one where you open your workbook.

V.B.
  • 6,236
  • 1
  • 33
  • 56
  • Thank you very much! When only one Excel process is running the code does work! This is good enough for me now. – xiphoid Mar 24 '16 at 14:11