是否可以为Google Sheets中附加的行添加格式(着色)(通过Google Apps脚本)



我有一个谷歌应用程序脚本,它可以将行从一张表复制到另一张表,执行各种转换。此逻辑最终使用sheet.appendRow(row-detail(将行放到新的工作表上。我希望这些新创建的行有一个背景色(我的意图是保持"latestColour",这样我就可以交替着色(。

那么,是否可以在appendRow方法本身中添加着色,或者很容易地确定append Row方法处理的范围,这样我就可以应用额外的逻辑来添加着色。

您可以使用条件格式

=and(A1<>"",A2="")

虽然我不确定我是否能正确理解你的情况,但从你的问题来看,我认为你可能在使用[Format]->谷歌电子表格中的[交替颜色]。并且,当通过放置值来附加新行时,您可能希望反映";"交替颜色";在附加行中。如果我的猜测是正确的,那么下面的示例脚本如何?

示例脚本:

function myFunction() {
const addValues = ["sample1", "sample2", "sample3"]; // This is a sample appending value. Please replace this for your value.
const sheetName = "Sheet1"; // Please set the sheet name.
// Retrieve banding object from the data range.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const b = sheet.getDataRange().getBandings();
if (b.length == 0) {
console.log("Bandings are not used.");
return;
}
// Append the value.
sheet.appendRow(addValues);
// Expand the range of banding.
b[0].setRange(sheet.getDataRange());
}
  • 运行此脚本时,将检索当前条带。并且,在附加值之后,通过包含附加的行来更新条带。在本示例中,即使追加了多行,也可以使用此脚本

注意:

  • 根据您的问题,我猜您的工作表中的数据范围中有一条带。请小心

参考文献:

  • getBandings((
  • setRange(范围(
  • 不幸的是,方法appendRow((没有接收格式化设置作为输入,只有一个值数组。

  • 然而,如果你想实现自己的逻辑,这里有一个建议:

示例代码:

function applyColorLastRow() {
var ss = SpreadsheetApp.getActive(); //get active sheets file 
var range = ss.getDataRange(); //get populated range, you may want to set a range manually if needed.
var lastRowNum = range.getLastRow(); //getting the last row index of the range.
var lastRowRange = ss.getRange(`${lastRowNum}:${lastRowNum}`); //narrowing the range (using A1 notation) to the last row only to apply color
var lastRowColor = lastRowRange.getCell(1,1).getBackgroundObject().asRgbColor().asHexString(); 
//Your row coloring logic here...
if (lastRowColor === '#ffffff'){ //toggling white/grey color as an example...
lastRowRange.setBackground('#cccccc'); //apply grey color to all cells in the last row range
} else {
lastRowRange.setBackground('#ffffff'); //apply white color to all cells in the last row range
};
}

相关内容

最新更新