我正在努力完成這個專案,但最后一部分讓我堅持了 2 天。我有一個 Google 表格,非常簡單,我只需要它按單元格的背景顏色自動排序。我按此順序需要 7 種顏色,并且我嘗試使用 Sort Range Plus 擴展名,它確實有效,但我無法弄清楚在編輯作業表時如何使用預先確定的引數呼叫它。然后我找到了一個應該完全滿足我需要的應用程式腳本,我想我首先啟用了 Sheets API,就像論壇所說的那樣,我相信我必須在兩個地方這樣做,但仍然是我運行以下代碼,我在第 25/26 行不斷收到錯誤:
錯誤:例外:物件不是 RgbColor 型別。
(匿名)@SortByColor.gs :26
(SortByColor)@SortByColor.gs:25
我不確定如何解決這個問題,因為它運行并獲取顏色然后出錯。我以前沒有使用過javascript,所以我希望更熟悉的人可以幫助我。也許問題是我錯誤地啟用了它或其他什么?如果其他人對相同的代碼沒有問題,我想我可能做錯了。這也是我第一次使用 Google Apps Script。
這是我一直在嘗試的代碼。請原諒注釋掉的部分 - 我正在使用我在 2 個不同執行緒中找到的代碼。
function SortByColor() {
const sheetName = "Patient Progress"; // Please set the sheet name.
//const a1Notation = "A1:A1099"; // Please set the sort range as a1Notation.
// 1. Retrieve the background colors from the cells.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
//const range = sheet.getRange(a1Notation);
var range = sheet.getRange(2, 1, ss.getLastRow(), ss.getLastColumn());
const backgrounds = range.getBackgroundObjects();
// 2. Create the request body for using the batchUpdate method of Sheets API.
/**
const startRow = range.getRow() - 1;
const startColumn = range.getColumn() - 1;
const srange = {
sheetId: sheet.getSheetId(),
startRowIndex: startRow,
endRowIndex: startRow range.getNumRows(),
startColumnIndex: startColumn,
endColumnIndex: startColumn range.getNumColumns(),
};**/
const sortColorOrder = ['#ea9999', '#f9cb9c', '#fff2cc', 'd9ead3', '#cfe2f3', '#d9d2e9',
'#fffff' ]; // This means that "red", "orange", "yellow", "green", "blue", "purple",
"white" in order.
const backgroundColorObj = backgrounds.reduce((o, [a]) => {
const rgb = a.asRgbColor()
return Object.assign(o, { [rgb.asHexString()]: { red: rgb.getRed() / 255, green:
rgb.getGreen() / 255, blue: rgb.getBlue() / 255 } })
}, {});
const backgroundColors = sortColorOrder.map(e => backgroundColorObj[e]);
const requests = [
{
sortRange: {
range: srange,
sortSpecs: [{ dimensionIndex: 0, sortOrder: "ASCENDING" }],
},
},
{
sortRange: {
range: srange,
//sortSpecs: [{backgroundColor: '#d9d2e9'}, {backgroundColor: '#d9ead3'},
{backgroundColor: '#fff2cc'}]
sortSpecs: backgroundColors.map((rgb) => ({ backgroundColor: rgb })),
},
},
];
// 3. Request to Sheets API using the request body.
Sheets.Spreadsheets.batchUpdate({ requests: requests }, ss.getId());
}
uj5u.com熱心網友回復:
從您的演示腳本中,我認為您可能已經使用了我的答案
顏色分配后:

顏色排序后:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457222.html
標籤:javascript 谷歌应用脚本 谷歌表格 谷歌表格 API
上一篇:如何更改活動標題?
