First time poster and newbie to writing Google Scripts. I have written an importrange script which is working successfully, but I would now like to include some form of error handling to display an alert depending on whether the importrange has run successfully or not. So, if it the function runs successfully to display a success message and if it fails to display an error message. All my attempts so far haven't worked and I'm struggling to identify how I incorporate the correct message depending on the outcome of the function running. Below is a copy of code. Any help or advice would be greatly appreciated.
Many thanks
function runsies() {
importRange(
//Nordics
"1Xrhx03ub1uXdeFsS0mFZa2zi5uZL-qcuQDbe9oIULQU",
"DATADUMP: LE!A2:I",
"1GY-FjVa1XFNpKiR7wx3tCtGUMC2FRbLTORj-wI3iBK8",
"Nordics - LE!A1"
);
importRange(
//UK
"13Y0NOJie1gYWXanQhtkSnTNsx4vt_bcqfUIXj0ePnac",
"DATADUMP: LE!A2:I",
"1GY-FjVa1XFNpKiR7wx3tCtGUMC2FRbLTORj-wI3iBK8",
"UK - LE!A1"
);
};
function importRange(sourceID, sourceRange, destinationID, destinationRangeStart){
// Gather Source range values
const sourceSS = SpreadsheetApp.openById(sourceID);
const sourceRng = sourceSS.getRange(sourceRange);
const sourceVals = sourceRng.getValues();
// Get Destiation sheet and cell location.
const destinationSS = SpreadsheetApp.openById(destinationID);
const destStartRange = destinationSS.getRange(destinationRangeStart);
const destSheet = destStartRange.getSheet();
// Clear previous data.
destSheet.clear();
// Get the full data range to paste from start range.
const destRange = destSheet.getRange(
destStartRange.getRow(),//Start Row
destStartRange.getColumn(),//Start Column
sourceVals.length,//Row Depth
sourceVals[0].length //Column Width
);
// Paste in the values
destRange.setValues(sourceVals);
SpreadsheetApp.flush();
};
CodePudding user response:
After reading articles online I've tried to use "try, catch", but this hasn't worked.
CodePudding user response:
Description
You can use a try {...} catch(err) {...} block to catch any error that may occur in your code or during exection. And you can use SpreadsheetApp.getUi().alert() to display a simple alert dialog box.
Code.gs
function importRange(sourceID, sourceRange, destinationID, destinationRangeStart){
try {
// Gather Source range values
const sourceSS = SpreadsheetApp.openById(sourceID);
//
// The rest of your code here
//
SpreadsheetApp.flush();
SpreadsheetApp.getUi().alert("Success");
}
catch(err) {
SpreadsheetApp.getUi().alert("Error: " err);
}
};
Reference