[英]In google sheets, how to replace #N/A in column A with corresponding value in column B
[英]Replace the G-Sheet column value, if the column value exceeds a threshold value, with the average of 'n' previous values in a Cell
您可以使用以下 GAS 代碼:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Fix values')
.addItem('Run fixer', 'fixValues')
.addToUi();
}
function fixValues() {
var n = 5;
var threshold = 55;
var values = SpreadsheetApp.getActiveRange().getValues();
for (var i=0; i<values.length; i++) {
if (values[i][0] > threshold && i==0)
values[i][0] = threshold;
if (values[i][0] > threshold && i>0) {
var startAvgIdx = (i-n >= 0) ? i-n : 0;
var sum = 0;
for (var j=startAvgIdx; j<i; ++j) sum += values[j][0];
var avg = sum / (i-startAvgIdx);
values[i][0] = avg;
}
}
SpreadsheetApp.getActiveRange().setValues(values);
}
這將在您的表格文檔頂部創建一個菜單,其中包含一個運行 function 的按鈕。 function 將在所選范圍內運行。 您可以在下面看到一個結果示例:
只剩下一個需要考慮的問題:如果初始值已經大於閾值怎么辦? 是否應該保持原樣,是否應該將其設置為閾值...? 在我的代碼中,我創建了它以在發生這種情況時設置為閾值,但可以隨意更改它( if (values[i][0] > threshold && i==0)
行之后的代碼)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.