在 Google 表格中,我正在尝试创建一个脚本,该脚本将从活动单元格中获取值并将该值粘贴到 B 列中包含字符串“HR”的任何单元格中。有任何想法吗?
1 回答
0
这还不错。您只需要了解 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
像这样盲目调用会覆盖你拥有的任何公式。这没什么大不了的,除了这包括超链接。您可以getFormulas
通过并行调用真正参与其中getValues
,然后根据每个单元格的原始内容决定setValue
是否调用。setFormula
于 2018-08-31T15:23:54.897 回答