diff --git a/ClosedXML/Excel/Cells/XLCellsCollection.cs b/ClosedXML/Excel/Cells/XLCellsCollection.cs index 2cd1490..0c2f9e8 100644 --- a/ClosedXML/Excel/Cells/XLCellsCollection.cs +++ b/ClosedXML/Excel/Cells/XLCellsCollection.cs @@ -212,22 +212,28 @@ { int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd; int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd; + int firstColumnUsed = finalColumn; + var found = false; for (int ro = rowStart; ro <= finalRow; ro++) { if (rowsCollection.TryGetValue(ro, out Dictionary columnsCollection)) { - for (int co = columnStart; co <= finalColumn; co++) + for (int co = columnStart; co <= firstColumnUsed; co++) { if (columnsCollection.TryGetValue(co, out XLCell cell) && !cell.IsEmpty(includeFormats) - && (predicate == null || predicate(cell))) - - return co; + && (predicate == null || predicate(cell)) + && co <= firstColumnUsed) + { + firstColumnUsed = co; + found = true; + break; + } } } } - return 0; + return found ? firstColumnUsed : 0; } public int LastRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func predicate = null)