Google sheets move focus from search box with keyboard shortcut

Viewed 504

How can I move focus from the search box back to the current (selected) cell using a keyboard shortcut? None of the pre-defined 'move focus' shortcuts appear to work. CTRL+ALT+SHIFT+M moves focus out of the search box, but to who knows where...

My macro to do this fails with 'Range not found'...

spreadsheet.getRange(spreadsheet.getActiveCell()).activate();

TIA.

1 Answers

You can press Esc to close the search box and make the last found cell the active cell. This works both in quick find Control+F and Edit > Find and replace Control+Shift+H.

To implement your own search function, you can use an onEdit(e) simple trigger like the one below.

The function uses a cell of your choice, say A1, as the search box. Choose View > Freeze to ensure the search box is always visible. Then enter the search string in the search box and press Tab to activate matching cells in the active sheet. You can also use a regular expression as a search string.

/**
* Simple trigger that runs each time the user hand edits the spreadsheet.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
  if (!e) {
    throw new Error('Please do not run the script in the script editor window. It runs automatically when you hand edit the spreadsheet.');
  }
  quickFind_(e);
}

/**
* Finds cells that match the regular expression entered in a magic cell.
*
* @param {Object} e The onEdit() event object.
*/
function quickFind_(e) {
  const sheets = /^(Sheet1|Sheet2|Sheet3)$/i; // use /./i to make the function work in all sheets
  const magicCell = 'A1';
  const sheet = e.range.getSheet();
  if (!e.value
    || e.range.getA1Notation() !== magicCell
    || !sheet.getName().match(sheets)) {
    return;
  }
  let searchFor;
  try {
    searchFor = new RegExp(e.value, 'i');
  } catch (error) {
    searchFor = e.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }
  const magicCellR1C1 = 'R' + e.range.rowStart + 'C' + e.range.columnStart;
  const data = sheet.getDataRange().getDisplayValues();
  const matches = [];
  data
    .forEach((row, rowIndex) => row
      .forEach((value, columnIndex) => {
        if (value.match(searchFor)) {
          const cellR1C1 = 'R' + (rowIndex + 1) + 'C' + (columnIndex + 1);
          if (cellR1C1 !== magicCellR1C1) {
            matches.push(cellR1C1);
          }
        }
      }));
  if (matches.length) {
    sheet.getRangeList(matches).activate();
  }
}
Related