locked
Loop Through Excel Named Range in C# RRS feed

  • Question

  • Hi - 

    I'm developing a excel application using VSTO and C#.

    So I have a named range ("myRange", rows count =1000, column count =2) on a sheet in the workbook and I just want to read through the  range row by row, and read the contents in column 1 and column 2.

    Any code would be much appreciated.

    Thanks,
    Mark

    Wednesday, February 25, 2009 6:10 AM

Answers

  •  
    I'm able to get the following to work:

    foreach (Excel.Range row in myRange.Rows)  
    {  
        Excel.Range cell = (Excel.Range)row.Cells[1, 1];  
        if (cell.Value2 != null)  
             System.Diagnostics.Debug.WriteLine(cell.Value2.ToString());  

    It always seems so easy once you get it ...
     
    Mark
    • Marked as answer by Mark from NJ Wednesday, February 25, 2009 2:57 PM
    Wednesday, February 25, 2009 2:56 PM

All replies

  •   Okay ... I got the following code to work

     Excel.Range rng = (Excel.Range)Globals.Sheet10.Application.get_Range("B45""C80");  
    for (int i = 0; i < rng.Count; i++)  
    {  
        Excel.Range cell = (Excel.Range)rng[i, 1];  
        MessageBox.Show(cell.Value2.ToString());  

    But on the first line, how can I reference a named range : "myRange" in the worksheet which goes from b45 to c80?
    Wednesday, February 25, 2009 2:04 PM
  •  
    I'm able to get the following to work:

    foreach (Excel.Range row in myRange.Rows)  
    {  
        Excel.Range cell = (Excel.Range)row.Cells[1, 1];  
        if (cell.Value2 != null)  
             System.Diagnostics.Debug.WriteLine(cell.Value2.ToString());  

    It always seems so easy once you get it ...
     
    Mark
    • Marked as answer by Mark from NJ Wednesday, February 25, 2009 2:57 PM
    Wednesday, February 25, 2009 2:56 PM