Technical Article

Sorting, Filtering, and Replacing Excel Rows in Delphi

A sorted sales list can look right even after its quantities have become detached from the order IDs. In Delphi, use HotXLS range sorting to move each record together, preview and apply Excel AutoFilter to control which rows are visible, and use Find and Replace on text cells to normalise labels.

HotXLS Sort, ApplyAutoFilter, and ReplaceText effects on an Excel order list
Sort moves whole records, ApplyAutoFilter changes which rows are visible, and ReplaceText rewrites the text in matching cells

One order per row

Put the sample below in A1:E9 on a worksheet named Sales. Units are numbers. Order ID stays text. The Pascal snippets assume Sheet is that TXLSXWorksheet from an open TXLSXWorkbook and that Variants and lxHandleX are in the uses clause. A dash means a blank cell. The order IDs give you something to compare across operations. Rows can move or disappear from view whilst each order still has the same identity.

Sales records in their original order
RegionItemUnitsOrder IDNotes
NorthWidget120SO-101Confirmed
SouthWidget45SO-102—
EastGadget210SO-103sample pack
NorthGadget88SO-104Hold
WestWidget175SO-105sample sample
SouthGadget30SO-106—
EastWidget175SO-107Sample pack
NorthGadget95SO-108Review

How do you sort Excel rows without separating the columns?

Sort the complete record rectangle. Give TXLSXRange.Sort the keys that say how it should move. Here A2:E9 covers all five fields whilst keeping the heading in row 1. The key list [3, 2] uses one-based worksheet columns: column C first, then column B. The direction list pairs True with Units for descending order and False with Item for ascending order. Sort C2:C9 alone and the quantities come out in order. The order IDs beside them are the wrong ones. If someone adds a discount column that belongs to the order, expand the rectangle to include it.

Sheet.Range['A2:E9'].Sort([3, 2], [True, False]);
Writeln('D2: ', VarToStr(Sheet.Cells[2, 4].Value),
  ', C2: ', VarToStr(Sheet.Cells[2, 3].Value));
Writeln('D3: ', VarToStr(Sheet.Cells[3, 4].Value),
  ', C3: ', VarToStr(Sheet.Cells[3, 3].Value));
Writeln('D4: ', VarToStr(Sheet.Cells[4, 4].Value),
  ', C4: ', VarToStr(Sheet.Cells[4, 3].Value));

Expected output:

D2: SO-103, C2: 210
D3: SO-105, C3: 175
D4: SO-107, C4: 175

SO-105 and SO-107 both hold 175 units and Widget, so the stable sort keeps SO-105, the earlier row, first. That order comes from this input. If two upstream feeds can deliver these orders in different sequences, add Order ID as a third key when a downstream process needs one fixed tie order. HotXLS moves the cell formatting with the field in the rectangle. Add a fill to the note on SO-105 before sorting if that note carries a visual status, and check that the fill lands with the order. Keep totals and other summary rows outside the data rectangle, and check any formula based on a particular record when spreadsheet position matters. The input cell types matter when you feed the sheet from another application. A quantity imported from a delimited source can arrive as the string '175', and the cell shows 175 either way. HotXLS sorts numeric keys and text keys by type. A text '175' is ordered as text, never between the numbers. Normalise Units when you import the file if the column is meant to be numeric. Microsoft's guide to sorting data in a range or table covers the Expand the selection prompt that Excel shows before it sorts one column away from the rest of its row.

Classic .xls uses TXLSWorksheet.SortRange from lxHandle. For these records, pass ClassicSheet.SortRange(2, 1, 9, 5, [3, 2], [True, False]), with the top-left and bottom-right coordinates in row, column order. The three lines below show how a Pascal open array is passed from C++Builder: the TXLSXRange.Sort overload receives two pointers, and each pointer is followed by the highest index of its array. A two-element array ends at index 1, which is the value that follows keys and descending. The call performs the sort from the Pascal example.

const int keys[] = {3, 2};
const bool descending[] = {true, false};
sheet->Range[WideString(L"A2:E9")]->Sort(keys, 1, descending, 1);

Why does an AutoFilter preview leave the rows visible?

TXLSXWorksheet.PreviewAutoFilterRows evaluates the criteria and counts matching data rows without changing worksheet row visibility. Use ApplyAutoFilter when the workbook should open with those criteria already reflected in its visible rows. Give SetAutoFilter the range A1:E9 to include the header row that receives the dropdowns. The filter column IDs are zero-based offsets from the range's first column, so Units is 2 and Region is 0. If the same block starts in column B, Units moves to worksheet column D. Its offset stays 2.

Sheet.SetAutoFilter('A1:E9');
Sheet.AddAutoFilterColumn(2, xlsxAfOpGreaterThan, '50',
  xlsxAfOpLessOrEqual, '200', True);
Sheet.AddAutoFilterColumn(0, xlsxAfOpNotEqual, 'North');

Writeln('preview matches: ', Sheet.PreviewAutoFilterRows(nil));
Writeln('row 2 hidden after preview: ', Sheet.RowHidden[2]);
Writeln('applied matches: ', Sheet.ApplyAutoFilter(True));
Writeln('row 2 hidden after apply: ', Sheet.RowHidden[2]);
Writeln('row 3 hidden after apply: ', Sheet.RowHidden[3]);
Writeln('row 4 hidden after apply: ', Sheet.RowHidden[4]);
Writeln('row 5 hidden after apply: ', Sheet.RowHidden[5]);

Expected output:

preview matches: 2
row 2 hidden after preview: FALSE
applied matches: 2
row 2 hidden after apply: TRUE
row 3 hidden after apply: FALSE
row 4 hidden after apply: FALSE
row 5 hidden after apply: TRUE

The True on the first rule joins the two Units comparisons with AND. SO-105 and SO-107 pass both. SO-103 has 210 units and falls outside the range, whilst SO-101 meets the numeric rule and falls out on Region. All eight orders still exist after applying the filter, and their hidden flags are stored with the worksheet. The example passes True to ApplyAutoFilter so matching data rows become visible even if some were already hidden, whilst False leaves previously hidden matching rows hidden within the filter range. That includes rows hidden manually or by an earlier filter. In that case the return value still counts matches, which can differ from the count of visible rows. The HotXLS AutoFilter execution guide covers more criteria and execution options.

Counting the cells a replacement changes

TXLSXWorksheet.FindText returns the first matching text cell in worksheet row and column order. ReplaceText with the simple overload changes all occurrences in each matching text cell and returns the number of cells whose value changed. Case-insensitive matching is the default for both calls. On the sorted sheet, a search for sample returns E2 even after filtering hides SO-103. An exact-case search for Sample returns E4. The filter narrows what you see, whilst these overloads scan worksheet text regardless of row visibility.

uses
  Variants, lxHandleX;

var
  Sheet: TXLSXWorksheet;

procedure ReplaceSampleNotes;
var
  Row, Col, Changed: Integer;
begin
  if Sheet.FindText('sample', Row, Col) then
    Writeln('first hit: row ', Row, ', col ', Col);
  if Sheet.FindText('Sample', Row, Col, True) then
    Writeln('exact-case hit: row ', Row, ', col ', Col);

  Changed := Sheet.ReplaceText('sample', 'trial');
  Writeln('cells changed: ', Changed);
  Writeln('E2: ', VarToStr(Sheet.Cells[2, 5].Value));
  Writeln('E3: ', VarToStr(Sheet.Cells[3, 5].Value));
  Writeln('E4: ', VarToStr(Sheet.Cells[4, 5].Value));
end;

Expected output from ReplaceSampleNotes:

first hit: row 2, col 5
exact-case hit: row 4, col 5
cells changed: 3
E2: trial pack
E3: trial trial
E4: trial pack

Three cells changed. Four occurrences were replaced, because SO-105 contains the word twice. These overloads look for substrings in literal text, so sample would also match sampler. For a production workbook, delimit the editing scope before you replace the first value. Use ReplaceTextIn to confine a rename to a known rectangle. The simple overloads compare the text a cell stores, which is what makes them a fit for a Notes column. Units stores numbers. A search never lands there however the column is formatted. To edit the text of a formula, pass [lxfSearchFormulas] in the options of ReplaceText, and the formula text itself is searched and replaced. If an edit lands in a filtered column, call Sheet.ApplyAutoFilter(True) again, because each call evaluates the criteria against the current cell values. This example leaves Units and Region alone.

When a full label has to match, add lxfWholeCell to the options for ReplaceTextIn. For example, Sheet.ReplaceTextIn('Hold', 'On hold', [lxfWholeCell], 2, 5, 9, 5) would update the Notes entry on SO-104 and leave a note such as Hold for Tuesday alone. Filtering needs a little more care if you intend to edit only visible records: visit the matching rows from the preview callback, or apply the filter and check RowHidden before replacing a value in each row. A rectangular replacement scope by itself still includes the hidden rows between its bounds.

A catalogue cleanup or a daily order export runs through these three calls too. The sort range holds a record ID, the preview count shows what the filter will keep, and the value returned by ReplaceText is the number of notes to review. A copy written with TXLSXWorkbook.SaveAs keeps the sorted order, the hidden rows, and the edited notes, so a reopened workbook still has SO-103 in row 2 behind the filter, SO-105 and SO-107 in rows 3 and 4, and trial trial in E3. If a report also totals visible units, the total for this input is 350. A regular SUM over all eight rows produces 938, which is valid for an all-orders total. The guide to SUBTOTAL, AGGREGATE, and hidden rows explains how to make the formula match the report's intent. For workbook and worksheet APIs in Delphi and C++Builder, see the HotXLS spreadsheet component.