Answers / Question 27

Dependent dropdown that works on every row (Google Sheets + Excel): the second list follows the first, row by row

How to make an Item dropdown show only the items for the Category picked in the same row, for every row: a tested Apps Script for Google Sheets that handles pasting and clears stale picks, a no-script helper-row method, and the single Excel list formula.

The problem

Column B has a Category dropdown (Fruit, Vegetables, Dairy) and column C should only offer the items for that row's category. You get it working for row 2, copy it down, and every row shows row 2's list. Or the second dropdown never changes, or it keeps an old pick like Milk after the category changed to Fruit.

Inspired by a public question on Stack Overflow. The problem above is described in our own words and the solution below is ours.

Why it happens

A dropdown's list is a fixed list or a fixed range. Neither app has a built-in "filter this list by the cell to the left" option, so every dependent dropdown is a workaround: either each row's list comes from a formula that looks at that row, or a script writes the right dropdown into each row. Copying a dropdown with an absolute range like $A$2:$A$20 gives every row the same list, and nothing clears the second cell when the first one changes.

All the methods below use one list layout: a tab called Lists with the category names across row 1 (Fruit in A1, Vegetables in B1, Dairy in C1) and each category's items listed underneath, with no gaps.

Google Sheets: a script that sets the right dropdown on each row

This is the sturdiest option in Sheets: there's no helper area for anyone to break, new rows work automatically, and pasting or filling a block of categories updates every row at once. When the category changes, an item that no longer fits is cleared; when the category is cleared, the item dropdown is removed.

  1. Build the Lists tab as above, and give column B a normal dropdown of the categories (Insert → Dropdown, Dropdown (from a range), =Lists!1:1).
  2. Extensions → Apps Script, paste the code and set DEP: the tab name, the Category and Item columns, and the header rows.
  3. Save. Then choose refreshAllDropdowns in the function menu and press Run once, to give rows that already have a category their dropdown. After that it runs by itself whenever someone changes a category. Re-run it after you edit the Lists tab.
Code.gsApps Script
// Dependent dropdowns on every row: the Item dropdown in column C only offers the items that
// belong to the Category picked in column B of the SAME row. Works for typing, pasting a block
// and filling down, and clears an Item that no longer fits when the Category changes.
// Lists tab layout: row 1 holds the category names (one per column), items are listed under each:
//   Lists!A1 = Fruit   B1 = Vegetables   C1 = Dairy
//   Lists!A2 = Apple   B2 = Carrot       C2 = Milk  ... and so on.
const DEP = {
  sheet: 'Orders',       // tab with the dropdowns
  parentColumn: 2,       // B: Category (a normal dropdown: Insert > Dropdown)
  childColumn: 3,        // C: Item (this script sets its dropdown, row by row)
  headerRows: 1,         // rows at the top to ignore
  listsSheet: 'Lists'    // tab with categories across row 1 and their items below
};

function onEdit(e) {
  if (!e || !e.range) {                       // pressed Run: there is no edit event
    console.log('onEdit runs by itself on real edits. Run refreshAllDropdowns() from the editor.');
    return 0;
  }
  const range = e.range, sheet = range.getSheet();
  if (sheet.getName() !== DEP.sheet) return 0;
  if (range.getColumn() > DEP.parentColumn || range.getLastColumn() < DEP.parentColumn) return 0;
  const first = Math.max(range.getRow(), DEP.headerRows + 1), last = range.getLastRow();
  if (last < first) return 0;
  return updateRows_(sheet, first, last - first + 1, true);   // never trust e.value: read the cells
}

// Run once from the editor after setting up (or after editing the Lists tab) to give every
// existing row the right dropdown. It doesn't clear any values.
function refreshAllDropdowns() {
  const sheet = SpreadsheetApp.getActive().getSheetByName(DEP.sheet);
  if (!sheet) throw new Error('No tab named "' + DEP.sheet + '"');
  const n = sheet.getLastRow() - DEP.headerRows;
  return n > 0 ? updateRows_(sheet, DEP.headerRows + 1, n, false) : 0;
}

// Category name (trimmed, any case) -> list of its items, read from the Lists tab in one call.
function readLists_() {
  const ls = SpreadsheetApp.getActive().getSheetByName(DEP.listsSheet);
  if (!ls) throw new Error('No tab named "' + DEP.listsSheet + '"');
  const v = ls.getRange(1, 1, Math.max(ls.getLastRow(), 1), Math.max(ls.getLastColumn(), 1)).getValues();
  const map = {};
  for (let c = 0; c < v[0].length; c++) {
    const key = String(v[0][c]).trim().toLowerCase();
    if (!key) continue;
    const items = [];
    for (let r = 1; r < v.length; r++) {
      const item = String(v[r][c]).trim();
      if (item && items.indexOf(item) < 0) items.push(item);   // skip blanks and repeats
    }
    map[key] = items.slice(0, 500);                            // a dropdown list holds up to 500 items
  }
  return map;
}

function updateRows_(sheet, first, n, clearStale) {
  const lists = readLists_();
  const parents = sheet.getRange(first, DEP.parentColumn, n, 1).getValues();
  const childRange = sheet.getRange(first, DEP.childColumn, n, 1);
  const children = childRange.getValues();
  const rules = [];
  let withList = 0, cleared = false;
  for (let i = 0; i < n; i++) {
    const items = lists[String(parents[i][0]).trim().toLowerCase()];
    const current = String(children[i][0]).trim();
    if (items && items.length) {
      rules.push([SpreadsheetApp.newDataValidation().requireValueInList(items, true).setAllowInvalid(false).build()]);
      withList++;
      if (clearStale && current && items.indexOf(current) < 0) { children[i][0] = ''; cleared = true; }
    } else {
      rules.push([null]);                                      // no (known) category: no dropdown
      if (clearStale && current) { children[i][0] = ''; cleared = true; }
    }
  }
  childRange.setDataValidations(rules);                        // one call for the whole block
  if (cleared) childRange.setValues(children);
  return withList;
}

Google Sheets without a script: a helper row per row

If you can't use scripts, put a formula in a spare area (here columns J to Z, which you can hide) that lays out each row's items across the row, and point the dropdown at it with a relative range:

In J2, then fill down as far as your rows goFormula
=IFERROR(TRANSPOSE(FILTER(INDEX(Lists!$A$2:$Z$100,0,MATCH($B2,Lists!$A$1:$Z$1,0)),INDEX(Lists!$A$2:$Z$100,0,MATCH($B2,Lists!$A$1:$Z$1,0))<>"")),"")

Then select C2:C500, open Data → Data validation, choose Dropdown (from a range) and enter =J2:Z2. Sheets adds dollar signs when you save; open the rule again and remove the $ in front of both row numbers, so C3 reads J3:Z3, C4 reads J4:Z4, and so on. The catch: inserted rows don't get the helper formula, and an old pick isn't cleared when the category changes (it just gets a red warning flag).

Excel: one list formula, no helper columns

Excel's Data Validation accepts a formula that returns a range, and a relative reference to B2 shifts for each row. Select C2:C500 (with C2 as the active cell), open Data → Data Validation, choose List and paste this as the Source:

Data Validation, List, Source (Category in B, Lists tab as above)Formula
=OFFSET(Lists!$A$2,0,MATCH($B2,Lists!$A$1:$Z$1,0)-1,COUNTA(INDEX(Lists!$A$2:$Z$100,0,MATCH($B2,Lists!$A$1:$Z$1,0))),1)

MATCH finds the category's column, COUNTA counts its items, and OFFSET returns exactly that many cells, so there are no blank entries at the bottom of the list. Excel may warn that the source "currently evaluates to an error" if B2 is still empty; click Yes. Adding an item at the bottom of a category's column shows up immediately.

Good to know

The script's logic is unit-tested against a simulated spreadsheet before publishing. Always try new automations on a copy of your sheet first.