4
votes

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
Have you seen Excel interop loading XLLs and DLLs I do not have Excel so I can't test it for F#.Guy Coder
@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

1 Answers

1
votes

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.