I have the following function that works well for small number of rows:
async function RemoveEmptyRows() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
var selectedRange = context.workbook.getSelectedRange();
var surroundingRegion = selectedRange.getSurroundingRegion();
var firstCell = selectedRange.getCell(0, 0);
firstCell.load(['columnIndex']);
surroundingRegion.load(['rowCount', 'columnCount']);
await context.sync();
var newRange = sheet.getRangeByIndexes(0, firstCell.columnIndex, surroundingRegion.rowCount, 1);
newRange.load(['address', 'rowCount', 'values']);
await context.sync();
var i = 0;
var loopRange = newRange.rowCount;
var counter = 0;
var cellText = "";
while (i < loopRange) {
cellText = newRange.values[i][0];
if (cellText == "") {
var entireRow = sheet.getRangeByIndexes(i - counter, 0, 1, surroundingRegion.columnCount);
entireRow.delete(Excel.DeleteShiftDirection.up);
counter++;
}
i++;
}
await context.sync();
});
}
The problem with this function is that it shifts the entire row up, row by row. There is another function (modified from ScriptLab) to remove duplicates, that works well with a much larger number of rows.
async function RemoveDuplicates() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
var selectedRange = context.workbook.getSelectedRange();
var firstCell = selectedRange.getCell(0, 0);
var surroundingRegion = selectedRange.getSurroundingRegion();
firstCell.load('columnIndex');
surroundingRegion.load('address');
await context.sync();
var columnIndex = firstCell.columnIndex;
const deleteResult = surroundingRegion.removeDuplicates([columnIndex], true);
deleteResult.load();
});
}
Is there a way to create something similar to the RemoveDuplicates function, but for EmptyRows?
Thanks.
So far Excel JS do not have a DeleteEmptyRows()
, but it sounds like a good suggestion, we will consider creating this API in the future.
Is that OK to sort the range? if yes, here is a workaround.
Firstly, sort the range, therefore the empty rows would stay together, then create a range that includes the empty rows, after that, you can call range.delete(up)
to remove the empty rows.