Google Apps 脚本 - 当有数千行时,根据 A 列的值将值插入 B 列
Google Apps Script - Insert values to column B based on values on column A, when there is thousands of rows
我有一个脚本需要改进。该脚本遍历 A 列上的所有行。然后,它根据值在下一个单元格中插入一个值。例如:如果单元格 A2 上的值为 4,9,则它会将 UNDER10 插入单元格 B2。有用。但是,它的工作速度如此之慢。如果我在 A 列上有数千行,有时脚本会超时。有人知道让这个脚本更快的方法吗?
下面是我的脚本:
function myFunction() {
const ss = SpreadsheetApp.getActive().getActiveSheet()
const lastRow = ss.getLastRow();
for (var i = 1; i < lastRow +1; i++) {
var value = ss.getRange(i,1).getValue();
var newValue = ss.getRange(i,2);
if (value < 10) {
newValue.setValue("UNDER10");
} else if (value < 20) {
newValue.setValue("UNDER20");
} else if (value > 20) {
newValue.setValue("OVER20");
}
}
}
这项改进应该有效。请注意,我假设 A 列包含数字(google sheet 将 4,9 称为字符串。因此,语句 if(value < 10)
不是真正有效的)。
为了测试我的代码,我使用了 4.9、14.9 等
function myFunction() {
const ss = SpreadsheetApp.getActive().getActiveSheet()
const lastRow = ss.getLastRow();
// get all the range at once
let range = ss.getRange(2, 1, lastRow -1, 2);
// get all the values in 2D array
let values = range.getValues();
// for each pair of values [price, custom value], calculate the custom value
values.forEach((value)=> {
// NOTE that i parse float out of price.
// Google sheet refer 4,9 as string (i assume you ment 4.9)
value[0] = parseFloat(value[0])
if (value[0] < 10) {
value[1] = "UNDER10"
} else if (value[0] < 20) {
value[1] = "UNDER20";
} else if (value[0] > 20) {
value[1] = "OVER20";
}
})
// set the new values into the spreadsheet
range.setValues(values)
}
如果您想要比较每一行中的每个数字(例如,在 'A2' 单元格中:if(4 < 10 && 9 < 10)
)请发表评论,我会相应地进行修复。
我有一个脚本需要改进。该脚本遍历 A 列上的所有行。然后,它根据值在下一个单元格中插入一个值。例如:如果单元格 A2 上的值为 4,9,则它会将 UNDER10 插入单元格 B2。有用。但是,它的工作速度如此之慢。如果我在 A 列上有数千行,有时脚本会超时。有人知道让这个脚本更快的方法吗?
下面是我的脚本:
function myFunction() {
const ss = SpreadsheetApp.getActive().getActiveSheet()
const lastRow = ss.getLastRow();
for (var i = 1; i < lastRow +1; i++) {
var value = ss.getRange(i,1).getValue();
var newValue = ss.getRange(i,2);
if (value < 10) {
newValue.setValue("UNDER10");
} else if (value < 20) {
newValue.setValue("UNDER20");
} else if (value > 20) {
newValue.setValue("OVER20");
}
}
}
这项改进应该有效。请注意,我假设 A 列包含数字(google sheet 将 4,9 称为字符串。因此,语句 if(value < 10)
不是真正有效的)。
为了测试我的代码,我使用了 4.9、14.9 等
function myFunction() {
const ss = SpreadsheetApp.getActive().getActiveSheet()
const lastRow = ss.getLastRow();
// get all the range at once
let range = ss.getRange(2, 1, lastRow -1, 2);
// get all the values in 2D array
let values = range.getValues();
// for each pair of values [price, custom value], calculate the custom value
values.forEach((value)=> {
// NOTE that i parse float out of price.
// Google sheet refer 4,9 as string (i assume you ment 4.9)
value[0] = parseFloat(value[0])
if (value[0] < 10) {
value[1] = "UNDER10"
} else if (value[0] < 20) {
value[1] = "UNDER20";
} else if (value[0] > 20) {
value[1] = "OVER20";
}
})
// set the new values into the spreadsheet
range.setValues(values)
}
如果您想要比较每一行中的每个数字(例如,在 'A2' 单元格中:if(4 < 10 && 9 < 10)
)请发表评论,我会相应地进行修复。