I have found other posts with similar issues: Opening file throws error but still works
Google API error, but still works
but unfortunately, I am so new to Google Sheets/GAS that I just can't take it from there. I'm hoping someone can assist with this error, and tell me how to change it? (I was initially hired to complete a Smartsheet project, but the client didn't actually have a Smartsheet project, she was just calling it that lol. It was actually a Google Sheets project, so I'm learning on the fly as best as I can, but I can't even format this code below correctly - ugh!)
The error I am receiving is this:
TypeError: Cannot read property 'changeType' of undefined
onChange @ SortByColorScript.gs:2
And the code is below:
function onChange(e){
if(e.changeType == 'EDIT' || e.changeType == 'OTHER'){
// your code here
const sheetName = "Patient Progress"; // Please set the sheet name.
// 1. Retrieve the background colors from the cells.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const range = sheet.getRange(3, 1, ss.getLastRow() - 1, ss.getLastColumn());
const backgrounds = range.getBackgroundObjects();
// 2. Create the request body for using the batchUpdate method of Sheets API.
// This means "red","orange","yellow","green","blue","purple","white" in that order.
const sortColorOrder = ['#ea9999', '#f9cb9c', '#fff2cc', '#d9ead3', '#cfe2f3', '#d9d2e9'];
const backgroundColorObj = backgrounds.reduce((o, [a]) => {
const rgb = a.asRgbColor();
const hex = rgb.asHexString();
return Object.assign(o, { [hex == "#ffffffff" ? "#ffffff" : hex]: { red: rgb.getRed()
/ 255, green: rgb.getGreen() / 255, blue: rgb.getBlue() / 255 } });
}, {});
const backgroundColors = sortColorOrder.map(e => backgroundColorObj[e] ||
"").filter(String);
if (backgroundColors.length == 0) return;
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 requests = [
{ sortRange: { range: srange, sortSpecs: [{ dimensionIndex: 0, sortOrder: "ASCENDING"
}] } },
{ sortRange: { range: srange, sortSpecs: backgroundColors.map(rgb => ({
backgroundColor: rgb })) } }
];
// 3. Request to Sheets API using the request body.
Sheets.Spreadsheets.batchUpdate({ requests: requests }, ss.getId());
}
else {
return;
}
}
Again, this IS working, but I'd like to not have any errors. I did enable the Sheets API. I'm so sorry about this formatting. No matter how I do it, it still looks wrong. I never had these issues on the C++ forum, not sure what my issue is, but I'm sorry.