Excel custom sorting using Office scripts

Ignacio Gil Garzon 0 Reputation points
2024-02-08T09:01:23.4666667+00:00

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.");
}

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
1,477 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
872 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,508 questions
0 comments No comments
{count} votes