c# counterpart of VBA for Excel

hi,

can anybody tell me the c# counterpart of the following Excel VBA code line:

ActiveSheet.UsedRange.Columns(1).Cells

i tried (and also its variations)

((Range)((Range)((Worksheet)((Excel.Application)app).ActiveSheet).UsedRange).Columns[Type.Missing,1]).Cells

but doesn't seem to work. no matter what i tried i got an exception. neither could i find anything on google.

i would appreciate any help.
thanks.


Answer this question

c# counterpart of VBA for Excel

  • A. Marshall

    Thank you very much!!!

    indeed it works now. but it seems a little bit strange. because VS tells gives me the following tip when i type the code for "Columns[":

    object Range[object RowIndex, object ColumnIndex]

    and also according to Excel VBA documentation there is no second option. anyway, thank you for your help!!

    cheers.

  • Evangelos

    Hello,

    I believe your code is throwing an exception because the first parameter of the Columns property (which essentially calls into the native Range collection) is not optional. You are passing in Type.Missing, but you must instead pass in a value.

    The following code works fine if you want to get the first column in the UsedRange property (this code selects the first column). I have reorganized the code to make it more readable, and to make it easier to determine where errors are occurring in the future.

    Microsoft.Office.Interop.Excel.Worksheet sheet1 =
    app.ActiveSheet as
    Microsoft.Office.Interop.Excel.Worksheet;
    Microsoft.Office.Interop.Excel.Range column1 =
    sheet1.UsedRange.Columns[1, System.Type.Missing] as
    Microsoft.Office.Interop.Excel.Range;
    column1.Cells.Select();

    Please note that this forum is for questions regarding features that are specific to the Visual Studio Tools for Office product. For questions that are strictly about accessing Excel's object model from C#, you will probably receive more responses at one of the following forums:

    Working with the Office Primary Interop Assemblies (PIA): office.developer.automation newsgroup

    http://msdn.microsoft.com/newsgroups/default.aspx dg=microsoft.public.officedev&lang=en&cr=US

    General Excel programming issues: excel.programming newsgroup

    http://msdn.microsoft.com/newsgroups/default.aspx dg=microsoft.public.excel.programming&lang=en&cr=US

    I hope this helps,

    McLean Schofield



  • c# counterpart of VBA for Excel