1,066 questions
Excel custom sorting using Office scripts
Ignacio Gil Garzon
15
Reputation points
I have an Office script that correctly selects the A column and sorts it's values alphabetically, but I can't find a way to first sort using a custom list of words (for example, sex).
I would want my values to first be sorted by this list and to be sorted alphabetically within these values.
function main(workbook: ExcelScript.Workbook) {
// Get the active worksheet and range
let worksheet = workbook.getActiveWorksheet();
let dataRange = worksheet.getUsedRange();
// Check if the data range has values in column A
if (dataRange.getColumnCount() < 1) {
throw new Error("No data found in Column A.");
}
// Define the range to sort, excluding the first 3 rows
let sortRange = dataRange.getOffsetRange(3, 0);
// Custom sorting order
const customOrder = ["Man", "Woman", "Other"];
// Sort values in column A in the custom order, excluding the first 3 rows
sortRange.getSort().apply([
{
key: 0, // Column A
ascending: true
}
]);
console.log("Values in Column A (excluding the first 3 rows) have been sorted in ascending order.");
}
Microsoft 365 and Office Development Office JavaScript API
Microsoft 365 and Office Development Other
4,375 questions
Microsoft 365 and Office Excel For business Windows
3,888 questions
Sign in to answer