views:

281

answers:

1

I'm currently trying to move some VB6 macros into a C# app and I'm having trouble setting the active cell using C#.

In VB6 its simply:

ActiveSheet.Range("L1").Select

Does anyone know what the C# equivalent is?

Cheers in advance.

+3  A: 

Here's a sample piece of code:

        Excel.Worksheet sht = (Excel.Worksheet)ActiveSheet;
        sht.Cells[3, 3] = "HELLO";

You can also capture ranges:

        Excel.Range rng = (Excel.Range)sht.Cells[3, 3];

I believe to you just the Select method as before to select a range, although I haven't tested this.

        rng.Select();

You can obviously streamline this and chain these statements together, with the right casting. I don't want to hazard a guess here as I've not got a VSTO project open in from of me.

EDIT

You should also be able to get a range from the sheet using get_Range:

        rng = sht.get_Range("A1", Type.Missing);

VSTO tends to return Objects most of the time, necessitating casts, but get_Range is an exception. Someone might be able to correct me as I am not a big user of VSTO (still VBA die-hard when it comes to Excel).

Joel Goodwin
Im so dense its unreal, I was trying the to to the rng.Select before actually assigning rng a cell! Thanks for making it obvious!
bowsa
Small correction: get_Range takes 2 arguments (for cases where you want to select a group of cells), and it's one of these nice cases where it actually returns the right object type (Excel.Range) and not an object that requires casting... var cell = sheet.get_Range("A1", Type.Missing);
Mathias
@Mathias, thanks - corrected. I guess I was misremembering the situation with one input - where the second has to be Missing.
Joel Goodwin