Вот объяснение, почему вы не получаете нужных результатов.
enum ColorConstants
{
vbYellow = 65535,
vbRed = 255
}
Excel.Application excel = new Excel.Application
{
Visible = true,
WindowState = Excel.XlWindowState.xlMaximized
};
Excel.Workbook book = excel.Workbooks.Add();
Excel.Worksheet sheet = book.Sheets[1] as Excel.Worksheet;
// We have initial range "E5:I9"
Excel.Range cells = sheet.Range[sheet.Cells[5, 5], sheet.Cells[9, 9]];
cells.Interior.Color = ColorConstants.vbYellow; //Color the range
// Now your goal is to get range "F6:G7" (relative to the sheet),
// which is range "B2:C2" (relative to "cells" range)
// Let's dissect why this isn't the result you need
// You try to achieve your goal with this code:
Excel.Range cells2 = cells.Range[cells.Cells[2, 2], cells.Cells[3, 3]];
cells2.Interior.Color = ColorConstants.vbRed;
// However, the result is incorrect:
// it gives you "J10:K11" range:
string addr = cells2.Address[0, 0]; //=> J10:K11
// Let's see why this happens.
// The thing is that the cell, returned by Cells,
// is relative to SHEET - and not to YOUR RANGE.
// Start cell (top-left): its address is "F6"
Excel.Range cell_start = cells.Cells[2, 2];
// End cell (bottom-rigth): its address is "G7"
Excel.Range cell_end = cells.Cells[3, 3];
// So, we have "F6:G7" address.
// Now we must imagine that our initial range "E5:I9" - and namely "E5" - is the start cell of the sheet.
// When you do it, our "F6:G7" relatively to "E5:I9" will be "J10:K11",
// because "F6:G7" goes OUTSIDE the boundaries of "E5:I9".
// If you calculate correctly, it will be our incorrect "J10:K11" range.
// This is why you get incorrect result.
// To calculate the offset correctly,
// you must imagine your range as a small worksheet.
// For instance, for our range "E5:I9":
// • "E5" (statrt cell) can be referred to as:
// 1) cells.Cells[1]
// 2) cells.Cells[1, 1]
// 2) cells.Cells[1, "A"]
// 3) cells.Cells["A1"]
// • "F6" (end cell) can be referred to as:
// 1) cells.Cells[7]
// 2) cells.Cells[2, 2]
// 3) cells.Cells[2, "B"]
// 4) cells.Range["B2"]
// Thus, we need another approach:
cells2 = cells.Range["B2"].Resize[2, 2];
cells2 = cells.Cells[2, 2].Resize[2, 2];
cells2 = cells.Range["B2:C3"];
cells2.Interior.Color = ColorConstants.vbRed; //Color the range