Once you get a reference to a worksheet object (after starting excel and opening the file with your data), you can use the Range
member to get a specified cell. Then you can use Value2
property to get a value (e.g. string/double), which also returns the result of a formula. To get the formula, you can use Formula
member.
I didn't find any good way for testing whether the value is automatically calculated or not, but you can check if the Formula
value starts with the =
character. If you really only need as simple formulas as the one you describe (without parentheses etc.) then a simple regular expression should do the trick:
let reg = new Regex("=([A-Z]+[0-9]+)([^A-Z0-9]+)([A-Z]+[0-9]+)")
let getInfo (cell:Range) =
let formula = cell.Formula.ToString().Replace(" ", "")
match formula.StartsWith("="), cell.Value2 with
| true, _ ->
let g = reg.Match(formula).Groups
Formula(g.Item(1),g.Item(2),g.Item(3))
| :? float as n -> Float(n)
| :? string as s -> String(s)
| _ -> Empty
This returns a value of the following data type which covers all your cases:
type CellInfo =
| Empty
| Float of float
| String of string
| Formula of string * string * string
BTW: To load an excel in F# Interactive, you need something like this:
#r "Microsoft.Office.Interop.Excel.dll"
// Run Excel as a visible application
let app = new ApplicationClass(Visible = true)
// Create new file using the default template
let workbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
// Get the first worksheet
let worksheet = (workbook.Worksheets.[1] :?> _Worksheet)