gpt4 book ai didi

javascript - Google Sheet 脚本读取单元格 "a"并根据单元格 "b"值写入单元格 "a"

转载 作者:行者123 更新时间:2023-12-01 01:54:18 25 4
gpt4 key购买 nike

大家早上好,

我需要为 Google 表格编写一个脚本,检查该行中的单元格是否包含值,然后将值写入该行的列中。例如,如果第 2 行 G 列中的单元格的值不是“”,请在第 2 行 C 列的单元格中写入“新问题”。到目前为止,我已经这样做了:

// Purpose: To populate cell in Column G if another in row cell contains 
// something other than null, or ""

function formatSpreadsheet() {
var sheet = SpreadsheetApp.getActive();
var data = sheet.getRange("C3:1000").getValues();

if (data !== "") {
sheet.getRange("G3:G1000").setValue("New Issue");

}
}

问题在于,如果在 C3 - C1000 中找到某个值,则会将“新问题”写入范围 G3 - G1000 中的所有单元格。我需要它只将其写入相应的行。因此,如果 C4 有值,则 G4 应设置为“新问题”,如果 C5 有值,则 G5 应设置为“新问题”,依此类推。

希望这是有道理的,我可以尝试尽可能地澄清它。我不知道“IF 语句”在这种情况下是否有帮助,或者我是否需要 for every 循环。遗憾的是我不知道如何使用它们。感谢您的帮助!

最佳答案

针对此请求的 Apps 脚本解决方案需要检查每个数组索引,并写入其他范围中的相应索引。为了最大限度地提高速度,我们希望尽可能使用批处理操作 getValues()setValues。一种可能的解决方案如下所示:

function setNewIssueLabels() {
const sourceRangeA1 = "C3:C1000", destStart = "G3";

const sheet = SpreadsheetApp.getActive().getActiveSheet(),
source = sheet.getRange(sourceRangeA1).getValues();
if (!source.length || source[0].length !== 1)
throw new Error("Expected single-column source range with at least 1 row");

// Include the original row index in the array.
const inputs = source.map(function (row, index) {
row.unshift(index);
return row;
})
// Keep rows where the 2nd index (the original content) is not a null string.
.filter(function (iRow) {
return iRow[1] !== "";
});

var dest = sheet.getRange(destStart);
if (dest.getNumRows() < source.length)
dest = dest.offset(0, 0, source.length, 1)
const outputs = dest.getValues();

// For every row in 'inputs' (read: every row in the source range that
// has a value), do stuff.
inputs.forEach(function (iRow) {
var originalIndex = iRow[0];
// var originalContent = iRow[1];
// var isActualNewIssue = outputs[originalIndex] === "";
// if (isActualNewIssue) {
outputs[originalIndex] = "New Issue";
// } else {
// foo();
// }
});

/**
* Overwrite the contents of the destination range with the 'outputs' values,
* which will be whatever was previously there, and possibly additional
* cells with "new Issue"
*/
dest.setValues(output);
}

我添加并注释掉了一些逻辑,用于确定该值是否在上次调用函数时存在,或者是否是真正的新值。

关于javascript - Google Sheet 脚本读取单元格 "a"并根据单元格 "b"值写入单元格 "a",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com