首页 > 解决方案 > 谷歌表格使用键盘快捷键将焦点从搜索框移开

问题描述

如何使用键盘快捷键将焦点从搜索框移回当前(选定)单元格?预定义的“移动焦点”快捷方式似乎都不起作用。CTRL+ALT+SHIFT+M 将焦点移出搜索框,但谁知道在哪里...

我执行此操作的宏因“找不到范围”而失败...

电子表格.getRange(spreadsheet.getActiveCell()).activate();

TIA。

标签: google-apps-scriptgoogle-sheetskeyboard-shortcuts

解决方案


您可以按Esc关闭搜索框并使最后找到的单元格成为活动单元格。这适用于快速查找Control+FEdit > Find and replace Control+Shift+H

要实现自己的搜索功能,您可以使用如下所示的onEdit(e) 简单触发器

该函数使用您选择的单元格,例如A1,作为搜索框。选择“查看”>“冻结”以确保搜索框始终可见。然后在搜索框中输入搜索字符串并按Tab以激活活动工作表中的匹配单元格。您还可以使用正则表达式作为搜索字符串。

/**
* 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();
  }
}

推荐阅读