Automating Multi-Column Data Sorting in Google Sheets for Enhanced Data Management

Automated multi-column sorting in Google Sheets, with data flowing to ecommerce platforms.
Automated multi-column sorting in Google Sheets, with data flowing to ecommerce platforms.

In the fast-paced world of ecommerce, maintaining impeccably organized data is not just a best practice—it's a necessity. From managing product catalogs and inventory levels to tracking customer orders and supplier communications, the ability to quickly access and analyze information can significantly impact operational efficiency. Google Sheets often serves as a flexible backbone for many of these tasks. However, manually sorting large or frequently updated datasets can quickly become a bottleneck. This is where the power of Google Apps Script, particularly the onEdit trigger, transforms a static spreadsheet into a dynamic, self-organizing data management tool.

The Power of Automated Sorting with onEdit

Automating data sorting ensures that your most critical information is always presented logically, without manual intervention. The onEdit function in Google Apps Script is a simple trigger that executes a script whenever a cell in your spreadsheet is edited. This capability is ideal for scenarios where you want data to re-sort automatically after a new entry or an update.

A common point of confusion for those new to Apps Script is attempting to run an onEdit function directly from the script editor. Because onEdit functions rely on an 'event object' (e or event) that is only generated when a genuine edit occurs in the sheet, running it manually will often result in an error like "Cannot read properties of undefined (reading 'source')". These functions are designed to be triggered by user actions, not manual execution.

Implementing Multi-Column Sorting

The core of automated sorting lies in the range.sort() method. While sorting by a single column is straightforward, the real power comes from sorting by multiple criteria—for instance, sorting by date first, then by time for entries on the same date. This is achieved by passing an array of sort objects to the sort() method, where each object specifies a column and its sort order (ascending or descending).

A basic multi-column sort might look like this:

function onEdit(event) {
  var w = event.source.getSheetByName("Case Tracker");
  var c = w.getActiveCell();
  var srtby1 = 5; // Column E for date
  var srtby2 = 6; // Column F for time
  var t = "A10:J115"; // The data range to sort

  if (c.getColumn() == srtby1) {
    var range = w.getRange(t);
    range.sort([
      { column: srtby1, ascending: true },
      { column: srtby2, ascending: true }
    ]);
  }
}

In this example, the script checks if an edit occurred in column 5 (srtby1). If so, it sorts the specified range (A10:J115) first by column 5 in ascending order, then by column 6, also in ascending order.

Building a Robust Automation Solution

While the basic script works, a truly robust solution incorporates several best practices to enhance reliability and maintainability:

  • Prevent Manual Execution Errors: Add a check at the beginning of your onEdit function to prevent it from running if the event object is undefined, which happens during manual execution from the script editor. if (!e) throw "Do not run from Editor";
  • Target Specific Sheets and Ranges: Ensure the script only acts on the intended sheet and within the actual data range. This prevents unintended sorting on other sheets or header rows.
  • Dynamic Column Identification: Hardcoding column numbers (e.g., column 5, column 6) makes scripts fragile. If columns are reordered, the script breaks. A better approach is to identify sort columns by their header titles, dynamically mapping them to their current column numbers.
  • User Feedback: Use e.source.toast() to provide non-intrusive notifications to the user when the script executes, confirming the sort operation or indicating an error.
  • Constants for Configuration: Define key parameters like sheet names, header rows, and sort criteria as constants at the top of your script. This makes the script easier to read, modify, and manage without digging into the core logic.

Step-by-Step Implementation Guide

  1. Open Google Apps Script: In your Google Sheet, go to Extensions > Apps Script.
  2. Paste the Script: Delete any existing code in the Code.gs file and paste the comprehensive script provided below.
  3. Configure Constants: Adjust the SHEETNAME_TRACKER, RANGE_HEADERROW, FIRST_DATA_ROW, and SORTBY_TITLES constants to match your specific spreadsheet structure and desired sort criteria.
  4. Save the Script: Click the floppy disk icon (Save project).
  5. Test: Make an edit in one of the designated sort columns (e.g., 'Next Contact' or 'BCT (CST)') within your data range. The sheet should automatically re-sort, and a 'AUTOSORTED' toast notification should appear.

Comprehensive Best Practice Script for Automated Multi-Column Sorting

//@OnlyCurrentDoc

// Adjust these to your actual scenario
const SHEETNAME_TRACKER = 'Dummy Tracker'; // Name of the sheet to apply sorting
const RANGE_HEADERROW = 'A4:J4'; // Range containing your column headers
const FIRST_DATA_ROW = 10; // The first row where your data begins
const SORTBY_TITLES = [
  {title: 'Next Contact', ascending: true},
  {title: 'BCT (CST)', ascending: true}
];

/**
 * Triggered automatically on any edit in the spreadsheet.
 * Orchestrates the sorting logic based on the edit event.
 * @param {GoogleAppsScript.Events.SheetsOnEdit} e The event object from the onEdit trigger.
 */
function onEdit(e) {
  // Prevent script from running if triggered manually from editor without an event object.
  if (!e) throw "Do not run from Editor";

  const sheet = e.range.getSheet();

  // Exit if the edit is not in the designated tracking sheet.
  if (sheet.getName() !== SHEETNAME_TRACKER) return;

  // Exit if the edit is in a header row or above the data range.
  if (e.range.getRow() < FIRST_DATA_ROW) return;

  // Retrieve headers to dynamically find column numbers.
  let headerRange = sheet.getRange(RANGE_HEADERROW);
  let headers = headerRange.getValues()[0];
  let editColumn = e.range.getColumn();
  let doTheSort = false;
  let errorOccurred = false;

  // Map sort titles to their current column numbers and check if the edited column is a sort column.
  let sortByColumns = SORTBY_TITLES.map(col => {
    if (errorOccurred) return; // Stop processing if an error has already occurred

    let sortByColumnIndex = headers.indexOf(col.title) + 1; // +1 because indexOf is 0-based, column is 1-based

    if (!sortByColumnIndex) {
      errorOccurred = true;
      doTheSort = false;
      e.source.toast(`Column header [${col.title}] was not found!`, 'AUTOSORT ERROR');
      return;
    }

    // If the edited column is one of our designated sort columns, trigger the sort.
    if (editColumn === sortByColumnIndex) {
      doTheSort = true;
    }
    return {column: sortByColumnIndex, ascending: col.ascending};
  });

  // If no error occurred and the edit was in a sort column, proceed with sorting.
  if (!errorOccurred && doTheSort) {
    let lastDataRow = sheet.getLastRow();
    // Define the range of data to be sorted, starting from the first data row.
    let sortRange = headerRange.offset(FIRST_DATA_ROW - headerRange.getRow(), 0, lastDataRow - FIRST_DATA_ROW + 1);
    sortRange.sort(sortByColumns);
    e.source.toast(`Your data was sorted automatically.`, 'AUTOSORTED');
  }
}

This script represents a robust solution for automated multi-column sorting. By dynamically identifying columns based on their headers, it is resilient to changes in spreadsheet structure, ensuring your data remains consistently organized. The inclusion of user feedback and error handling makes it user-friendly and reliable for day-to-day operations.

Automating tasks like multi-column sorting in Google Sheets significantly streamlines data management, freeing up valuable time for ecommerce professionals. Whether you're tracking product updates, managing orders, or monitoring inventory, ensuring your data is always perfectly organized is crucial for informed decision-making. Tools like Sheet2Cart (sheet2cart.com) extend this automation further, allowing you to seamlessly sync your organized Google Sheets data, including product and inventory details, directly with your online store platforms like Shopify or WooCommerce. This powerful combination of automated sheet management and direct store integration ensures your ecommerce operations run smoothly, with accurate and up-to-date information always in sync.

Share:

Ready to scale your blog with AI?

Start with 1 free post per month. No credit card required.