This problem has me completely puzzled.
I have a Excel document which loads in just fine. It has rows, columns and data and I want to iterate through the rows. But EPPLus is odd.
I take the second row:
ExcelRange range1 = worksheet.Cells[2, worksheet.Dimension.Start.Column, 2, worksheet.Dimension.End.Column];
Which gives me {A2:D2}
Splendid! so far so good but then I want the first cell of the row:
ExcelRange range2 = range1[1,1];
Which give me {A1}
and to make matter worse, the value of range1
has also changed to {A1}
instead of the row I selected.
How can I resolve this issue and take a ExcelRange from an ExcelRange?
This has me completely puzzled .... thanks for anyhelp
The Range object can consist of individual cells or groups of cells. Even an entire row or column is considered to be a range. Although Excel can work with three dimensional formulas the Range object in VBA is limited to a range of cells on a single worksheet.
If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.
From the VBA IntelliSense list, choose “Value” property to get the value from the mentioned cell. Now the variable “CellValue” holds the value from the cell A1. Show this variable value in the message box in VBA. Ok, run the code and see the result in a message box.
When referring to a spreadsheet, the range or cell range is a group of cells within a row or column. For example, in the formula =sum(A1:A10), the cells in column A1 through A10 are the range of cells that are added together. This type of range is referred to as an adjacent range since all of the cells are together.
I did have the same problem, to get the correct start cell:
var range2 = worksheet.Cells[range1.Start.Row, range1.Start.Column];
And the same for the bottom right cell:
var range3 = worksheet.Cells[range1.End.Row, range1.End.Column];
If you look at the code behind the ExcelRange
Indexer you will see that the get
will actually set the base address (the nested else
):
public ExcelRange this[string Address]
{
get
{
if (_worksheet.Names.ContainsKey(Address))
{
if (_worksheet.Names[Address].IsName)
{
return null;
}
else
{
base.Address = _worksheet.Names[Address].Address;
}
}
else
{
base.Address = Address;
}
_rtc = null;
return this;
}
}
Why they did it this way I am not sure (I assume there its an implementation detail). But that would explain why referencing another address changes the selected range. So, like Benexx said, have to do a direct reference from the Cells
collection of the Worksheet
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With