1

I am trying to get the data in an Excel named range for an F# based add-in. I want to be able to use named ranges anywhere in the workbook, not just a specific worksheet.

let xlRange (xl:Microsoft.Office.Interop.Excel.Application, name:string) =
    let name_list = xl.ThisWorkbook.Names:Microsoft.Office.Interop.Excel.Names
    let mutable result=null
    for n in name_list do
        let nn = n :?> Microsoft.Office.Interop.Excel.Name
        if nn.Name = name then
            let range=nn.RefersToRange
            result <- range.Value2 :?> obj[,]
    result

The above code works, but I don't like it because I had to use a mutable and imperative style. The problem is the Excel.Names collection doesn't behave very well. For example

let name_seq = Seq.toList name_list

gives

The type 'Names' is not compatible with the type 'seq<'a>'

Is there a more F# idiomatic way of doing this?

1
  • Try Seq.toList (Seq.cast name_list), maybe even specify a type (i.e. let name_seq : ... = ...).
    – Ramon Snir
    Jul 7, 2012 at 19:23

2 Answers 2

1

You should use Seq.cast to cast name_list to a typed sequence.

The advantage is obvious; you have better interoperability with F# and could use high-order functions in Seq module instead of imperative for loop.

let xlRange (xl: Microsoft.Office.Interop.Excel.Application, name: string) =
    xl.ThisWorkbook.Names
    |> Seq.cast<Microsoft.Office.Interop.Excel.Name> 
    |> Seq.tryPick (fun n -> if n.Name = name 
                             then Some (n.RefersToRange.Value2 :?> obj[,])
                             else None)

The return type now is obj[,] option which gives you type safety for free.

1
  • Thanks this what I tried at first but I get the type 'Names' is not compatible with the type 'IEnumerable' Jul 9, 2012 at 10:27
0

I couldn't use the Seq. things directly because of incompatible types. I made this function which aims to convert the collection to an F# list which I could then process as above. It compiled fine but I didn't test because...

let xlNamesToList names =
    let rec xlNameList_r (names:Microsoft.Office.Interop.Excel.Names) idx =
        if idx>names.Count then // should this be >= ?
            []
        else
            names.Item(idx)::xlNameList_r names (idx+1)
    xlNameList_r names 0

...then I found a simpler way to do it directly:

let xlRange (xl:Microsoft.Office.Interop.Excel.Application, name:string) =
    try
        let r=xl.ThisWorkbook.Names.Item(name :> obj).RefersToRange
        Some(r.Value2 :?> obj[,])
    with
        | _ -> None

Thanks for the help guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.