将活动单元格复制到包含字符串的其他单元格

Copy active cell to other cells containing string

在 Google 表格中,我正在尝试创建一个脚本,该脚本将从活动单元格中获取值并将该值粘贴到包含字符串 "HR" 的 B 列中的任何单元格。有什么想法吗?

这还不错;您只需要围绕 Apps Script 和 Javascript 中的一些概念进行思考即可使其高效。但首先让我们从天真的方法开始!

function firstTry() {
  var activeSheet = SpreadsheetApp.getActiveSheet();  // whatever is open
  var activeCell = SpreadsheetApp.getCurrentCell();   // this is a single-cell range
  var activeCellValue = activeCell.getValue();        // could be a string, number, etc
  // Now let's look in column B for stuff to change
  for (var i = 1; i <= activeSheet.getLastRow(); i++) {
    var cell = activeSheet.getRange("B" + i);
    var val = cell.getValue();
    var valStr = String(val);                        // We could have gotten a number
    if (valStr.indexOf("HR") != -1) {
      cell.setValue(activeCellValue);
    }
  }
}

这可能会奏效,但效率不高:每次调用 getValue() 或 setValue() 都需要一些时间。最好一次获取所有值,然后在我们满意时粘贴回修改后的 B 列:

function improvement() {
  var activeSheet = SpreadsheetApp.getActiveSheet();  // whatever is open
  var activeCell = SpreadsheetApp.getCurrentCell();   // this is a single-cell range
  var activeCellValue = activeCell.getValue();        // could be a string, number, etc
  // Now let's look in column B for stuff to change
  var rowsWithData = activeSheet.getLastRow() - 1;
  var colBRange = activeSheet.getRange(1,             // start on row 1
                                       2,             // start on column 2
                                       rowsWithData,  // this many rows
                                       1);            // just one column
  // Let's get the data as an array of arrays. JS arrays are 0-based, btw
  var colBData = colBRange.getValues();               
  for (var i = 0; i < colBData.length; i++) {
    var val = colBData[i][0];                         // row i, first column
    var valStr = String(val);                         // We might have gotten a number
    if (valStr.indexOf("HR") != -1) {
      colBData[i][0] = activeCellValue;               // modify copied data
    }
  }
  // Lastly, write column B back out
  colBRange.setValues(colBData);
}

您可以使用花哨的过滤函数来更进一步,而不是显式循环遍历数据,但这开始变得不那么清晰了。

注意事项 正如 OP 在下面的评论中指出的那样,像这样盲目调用 setValues 将为您拥有的任何公式铺平道路。这没什么大不了的,除非这包括超链接。您 可以 通过在 getValues 的同时调用 getFormulas 真正参与进来,然后决定是调用 setValue 还是 setFormula每个单元格的原始内容。