tags:

views:

321

answers:

3

Using .NET's Office interop libraries, does anybody know the best way to convert back and forth between strings (eg "A57", "$L$2:$M:$3") and corresponding objects of type Excel.Range?

Bonus points if it also works with "named ranges".

A: 

Use the Range property of a Worksheet object, and pass Type.Missing as the second parameter.

For example:

Range range = sheet.get_Range("$L$2:$M:$3", Type.Missing);

This also supports named ranges.

EDITED

SLaks
This is what I want, though I am interested in the inverse operation(Range to string) as well.
mcoolbeth
Cast the Range's `Name` property to a `Name` object and look at the properties.
SLaks
Can you think of any reason for Range not to appear among the visible properties of a Worksheet in Visual Studio?
mcoolbeth
It won't build if I type "Range" myself. I see get_Range, but the arguments/behaviour are not well documented.
mcoolbeth
You can call `get_Range`; see my edit.
SLaks
A: 

This doesn't answer your question directly but may provide you with an answer...

As I discuss on my blog entitled, Tribal Knowledge: Working with Office Interops, one way to divine the inner workings of any office document and how to manage it via the interops is to record a macro of the process needed. Once done examine the vba code, it will show settings changes and other items of interest that can lead the way through the tribal knowledge of the interops. Most the object calls are the same under the covers...good luck.

OmegaMan
A: 

If what you are trying to get is the actual contents of the cell, use the Value2 property. Here's some code that examines the cell value type and does different things accordingly.

Excel.Range cell = (Excel.Range)sheet.UsedRange[row, col];
if (cell.Value2 != null)
{
    switch (Type.GetTypeCode(cell.Value2.GetType()))
    {
        case TypeCode.String:
            string formula = cell.Value2;
            break;
        case TypeCode.Double:
            double amt = (Double)cell.Value2;
            break;
    }
}

cell.Value2 = amt + someotheramt;

HTH

ScottTx