F# Excel Interop: Marshal.GetActiveObject("Excel.Application") does not work

Viewed 442

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!

1 Answers
Related