Диапазон возвращает неправильный набор ячеек - PullRequest
0 голосов
/ 26 мая 2020

Я использую Excel Interop и пытаюсь вернуть диапазон ячеек относительно первого диапазона ячеек, который я получил с рабочего листа. Проблема в том, что вторая выборка диапазона не дает мне ожидаемых ячеек. Вот код:

Range cells = xlWorkSheet.Range[
    xlWorkSheet.Cells[5, 5],
    xlWorkSheet.Cells[9, 9]
];

Range cells2 = cells.Range[cells[2, 2], cells[3, 3]];

Во втором вызове Range я ожидал получить ячейки от [6, 6] до [7, 7] (то есть относительно рабочего листа). Вместо этого я получаю от [10, 10] до [11, 11].

Если я получаю отдельную ячейку, я получаю ожидаемую:

Range c1 = cells.Cells[2, 2];

Это возвращает мне [6 , 6] кл. Есть мысли о том, почему у меня такое поведение?

Ответы [ 2 ]

1 голос
/ 26 мая 2020

Вот объяснение, почему вы не получаете нужных результатов.

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
1 голос
/ 26 мая 2020

Да, Cells.Parent в вашем случае - это объект xlWorkSheet.

Для полноты информации имейте в виду, что вы можете использовать любое из следующего, и вы получите те же успешные результаты, которые хотели бы видеть:

Range cells2 = cells.Parent.Range[cells.Cells[2, 2], cells.Cells[3, 3]];

или

Range cells2 = xlWorkSheet.Range[cells.Cells[2, 2], cells.Cells[3, 3]];

или

Range cells2 = cells.Range[xlWorkSheet.Cells[2, 2], xlWorkSheet.Cells[3, 3]];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...