[英]How to get range and then set value in Google Apps Script
I am trying to run a function on edit that will look for the value 'c' in a range of cells and then replace it with the word 'Closed'.我正在尝试在编辑时运行一个函数,该函数将在一系列单元格中查找值“c”,然后将其替换为“关闭”一词。
This is what I have so far:这是我到目前为止:
function onEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getRange('CA12:CA15').getValues();
var closed = 'c'
for(var i=0; i<data.length;i++) {
if(data[i] == closed) {
Logger.log('yes')
Logger.log(data[i]);
}
}
}
So this is successfully logging 'yes' and the value 'c' when I have this value within the given range.因此,当我在给定范围内具有此值时,这将成功记录“是”和值“c”。 But how do I now replace this value?
但是我现在如何替换这个值?
I tried storing the range of data[i] using getRange() but it won't allow me to do this.我尝试使用 getRange() 存储数据范围 [i] 但它不允许我这样做。 If I can get this range then I know I can then use range.setValue('Closed') but a bit stuck at the moment.
如果我能得到这个范围,那么我知道我可以使用 range.setValue('Closed') 但现在有点卡住了。 I know I'm doing something very simple very wrong but any help would be great.
我知道我正在做一些非常简单非常错误的事情,但任何帮助都会很棒。
getValues
returns a 2 dimensional array ordered by rows and then columns. getValues
返回一个按行和列排序的二维数组。 You're accessing a 1D array with data[i]
data[i]
访问一维数组i
the index of array + start row is equal to the current row in loop. i
数组 + 起始行的索引等于循环中的当前行。if(data[i][0] == closed) { //2D
sheet.getRange('CA'+(12+i)).setValue('Closed');
}
var rng =sheet.getRange('CA12:CA15');
var data = rng.getValues();
var output = data.map(function(e) { return e[0] == closed ? ['Closed'] : e });
rng.setValues(output); //Single call
Try this:尝试这个:
function onEdit(e) {
var sheet = e.range.getSheet();
var editedCell=sheet.getRange(e.range.getRow(),e.range.getColumn()).getA1Notation();
var data = sheet.getDataRange().getValues();
var found=false;
var foundA=[];
for(var i=0;i<data.length;i++) {
if(data[i][2] == 'c') {
found=true;
foundA.push(i+1);
}
}
if(found){
Logger.log('Matches found in following rows of column C: %s\nCell Edited was: %s',foundA.join(','),editedCell);
}else{
Logger.log('No matches found');
}
}
For testing purposes you can use SpreadsheetApp.getUi().alert(Logger.getLog());
出于测试目的,您可以使用
SpreadsheetApp.getUi().alert(Logger.getLog());
to display Logger results.显示记录器结果。
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getRange('C2:C').getValues();
var name = valuetosearchincColumnC;
for(var i=0; i<data.length;i++) {
if(data[i] == name) {
var id = i + 2;// plus two bec i have a header
sheet.getRange(id,2).setValue('ValuetoChange');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.