Using Excel.Region.get_Range() within a range, gives unexpected behavior

Viewed 434

I am trying to access a range, within another range, in Excel C#, and getting unexpected behavior. In the first range, Cell[1,1].Value, gives the value of the first cell, in the range, as expected. However, in the "subrange", Cell[1,1].Value, does not give the value of the first cell in the subrange. Instead, it jumps down a few rows.

Microsoft documentation

namespace RangeRange
{
    class RangeRange
    {
        private Excel.Application excelApp = new Excel.Application();
        private Excel.Workbook workbook;
        private Excel.Worksheet worksheet;

        public int Load(string filepath)
        {
            workbook = excelApp.Workbooks.Open(filepath);
            worksheet = (Excel.Worksheet)workbook.Sheets[1];

            return 0;
        }

        public int Close()
        {
            // Shut down excel.exe
            workbook.Close();
            excelApp.Quit();

            return 0;
        }

        public int Process()
        {
            Excel.Range data_range = worksheet.UsedRange.Cells;
            int rows = data_range.Rows.Count;
            int cols = data_range.Columns.Count;

            // Get the range containing rows 3 through N.
            Excel.Range c1 = worksheet.Cells[3, 1];
            Excel.Range c2 = worksheet.Cells[rows, cols];
            Excel.Range range1 = (Excel.Range)worksheet.get_Range(c1, c2);

            string value1 = range1.Cells[1, 1].Value;

            Console.WriteLine(value1);

            ProcessRange(range1);

            return 0;
        }

        private int ProcessRange(Excel.Range my_range)
        {
            // Get a range, containing all rows, within my_range.
            int rows = my_range.Rows.Count;
            int cols = my_range.Columns.Count;

            Excel.Range c1 = my_range.Cells[1, 1];
            Excel.Range c2 = my_range.Cells[rows, cols];
            Excel.Range range2 = (Excel.Range)my_range.get_Range(c1, c2);

            string value2 = range2.Cells[1, 1].Value;

            Console.WriteLine(value2);

            return 0;
        }
    }
}

My input data is:

data.xlsx

The output is:

output window

1 Answers
Related