- 您想更改“A4:A8”范围内单元格的背景颜色,以使“C4”的下拉列表的值相同。
- 您希望使用 Google Apps 脚本实现此目的。
- 在您的脚本中,您不想使用事件对象。
如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。
修改点:
- 工作表对象可由
var sheet = SpreadsheetApp.getActiveSheet(); 写入。这样,您就可以使用sheet 来检索范围。
-
sheet.getRange("A4:A8") 和 sheet.getRange("C4") 可以使用一次。
- 在这种情况下,范围对象不能在循环中使用,因为
testRange.length返回null。
当以上几点反映到你的脚本中时,它变成如下。
模式一:
在此模式中,只有选定值的背景颜色更改为红色。 So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color.在这种情况下,“A”的背景颜色被重置。
修改脚本:
function onEdit3(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var testRange = sheet.getRange("A4:A8");
var testRangeValues = testRange.getValues();
var testCell = sheet.getRange("C4");
var testCellValue = testCell.getValue();
var backgroundColors = testRangeValues.map(function([a]) {return [a == testCellValue ? "Red" : ""]});
testRange.setBackgrounds(backgroundColors);
}
模式 2:
在此模式中,将保存所选值的背景颜色。 So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color.在这种情况下,“A”的背景颜色保持为红色。
修改脚本:
function onEdit3(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var testRange = sheet.getRange("A4:A8");
var testRangeValues = testRange.getValues();
var testCell = sheet.getRange("C4");
var testCellValue = testCell.getValue();
for (var i = 0; i < testRangeValues.length; i++) {
if (testRangeValues[i] == testCellValue) {
sheet.getRange("A" + (4 + i)).setBackground("Red");
break;
}
}
}
现代javascript:
您可以使用现代 javascript 语法。为此,您需要enable V8 runtime。之后就可以了
/**
*
* @param {GoogleAppsScript.Events.SheetsOnEdit} e
*/
const onEdit = e => {
const sheet = e.range.getSheet();
const value = e.range.getValue();
if (sheet.getName() == 'Sheet1' && e.range.getA1Notation() === 'C2') {
const range = sheet.getRange(2, 1, sheet.getLastRow() - 1, 1);
range.setBackgrounds(
range.getValues().map(row => [row[0] === value ? 'red' : ''])
);
}
};
参考资料:
如果我误解了您的问题并且这不是您想要的方向,我深表歉意。