I have a really simple script to pull the given tab name:
function sheetName() {return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();}
But this will not update when I change a tab's name. Is there any script that could be written to "re-execute" sheetName(), the function, in all places it is found in a spreadsheet? Would love to just pop in a button that could rerun sheetName() everywhere so that the tab names' references stay current.
I do see some old (~4 years) questions about this, but struggling to find something current. Apologies if this is duplicative!
You can install a trigger to run "On change" I tried editing a sheet tab, and the code did run.
function sheetNameReturn(e) {
Logger.log(e.changeType)
Logger.log('sheetName ran')
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Unfortunately, at the time of this post, the triggers are kind of buggy. If you install a trigger, and it doesn't run, you'll need to delete the trigger, close the window, and go through the process again and save it.
I changed the name of the function to sheetNameReturn I had a lot of trouble getting the trigger to run. I had to delete the trigger and install it again.
Keep Your Sheet Names the Same
If you'd like to keep your sheet names the same here's a script just for you. It utilizes a few scripts that I've been working on lately that allow you to save arrays and associative arrays in files rather than utilizing the PropertiesService. It may not be 100 percent bug free...but what is?
Code.gs
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('SaveSheetNames', 'SaveSheetNames')
.addToUi();
}
function SaveSheetNames()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shts = ss.getSheets();
var s = 'SheetNames:::DICT|***|';
for(var i = 0; i<shts.length;i++)
{
if(i>0){s += '~~~';}
s += shts[i].getSheetId() + '^^^' + shts[i].getSheetName();
}
saveFile(s);
}
function KeepSheetNames()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shts = ss.getSheets();
var SheetNamesA = getArrayByName('SheetNames');
for(var i = 0; i<shts.length;i++)
{
if(shts[i].getName() !== SheetNamesA[shts[i].getSheetId()])
{
shts[i].setName(SheetNamesA[shts[i].getSheetId()]);
}
}
}
ArrayFileStorage.gs
//A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |###|
//It returns an actual Associative Array
function getAssociativeArray(segment)
{
var segment = (typeof(segment))?segment:null;
var C = [];
var br = '<br />';
if(segment)
{
var A = segment.split('~~~');//Array of key^^^value strings [key^^^value,key^^^value,key^^^value...]
for(var i = 0;i<A.length;i++)
{
B=A[i].split('^^^');//KeyValueArray[key,val]
C[B[0]]=B[1];//Dictionary or Associative Array {key:'value',key:'value',key:'value'...}
}
}
return C;
}
//A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |###|
//It returns an actual Array
function getArray(segment)
{
var segment = (typeof(segment))?segment:null;
var br = '<br />';
if(segment)
{
var A=segment.split('~~~');
}
return A;
}
//The above functions are used within this function so that it can return either type of array object requested
function getArrayByName(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var br = '<br />';
if(name)
{
var data = loadFile('KeepSheetNames').split('|###|');//Array Data String two different forms possible
for(var i=0;i<data.length;i++)
{
var A = data[i].split('|***|');
var B = A[0];
var segment = A[1];
var nametype = B.split(':::');
if(nametype[0]==name)
{
if(nametype[1]=='DICT')
{
var obj = getAssociativeArray(segment)
}
if(nametype[1]=='ARRAY')
{
var obj = getArray(segment);
}
break;
}
}
}
return obj;
}
//This function just displays the data stored within the default data file by splitting it with |###|
function displayData()
{
s='';
var data = loadFile('KeepSheetNames').split('|###|');
for(var i=0;i<data.length;i++)
{
if(i>0)s+='<br />';
s+=data[i];
}
s += '<br /><input type="button" value="Exit" onClick="google.script.host.close();" />'
dispStatus('Display Data for Default File',s,1000,400);
}
//This function uses the saveFile function in Utility.gs to save data into default file.
//This function will also add a new array to the end
function saveArray(name,type,array)
{
var name = (typeof(name) !== 'undefined')? name : null;
var type = (typeof(type) !== 'undefined')? type : null;
var array = (typeof(array) !== 'undefined')? array : null;
var types = ['DICT','ARRAY'];
var isSaved = false;
var isAValidType = false;
for(var i=0;i<types.length;i++)
{
if(type == types[i])
{
isAValidType=true;
break;
}
}
if(name && isAValidType && array)
{
var data = loadFile('KeepSheetNames').split('|###|');
var datstr = '';
var idx = getIndexOf(name);
var str = convertArrayToString(name,type,array);
if(idx>-1)
{
data[idx]=str;
}
else
{
data.push(str);
}
for(var i = 0;i<data.length;i++)
{
if(i>0){datstr += '|###|';}
datstr += data[i];
}
isSaved=saveFile(datstr);
}
else
{
SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
}
return isSaved;
}
//This function gets the index of the requested named data array
function getIndexOf(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var idx = -1;
if(name)
{
var data = loadFile('KeepSheetNames').split('|###|');
for(var i=0;i<data.length;i++)
{
var nametype = data[i].split(':::');
if(name==nametype[0])
{
idx = i;
break;
}
}
}
return idx;
}
//Takes the real arrays and converts them to strings so that they can be saved.
function convertArrayToString(name,type,array)
{
var name = (typeof(name) !== 'undefined')? name : null;
var type = (typeof(type) !== 'undefined')? type : null;
var array = (typeof(array) !== 'undefined')? array : null;
var types = ['DICT','ARRAY'];
var ConvertedString='';
var isAValidType = false;
for(var i=0;i<types.length;i++)
{
if(type == types[i])
{
isAValidType=true;
break;
}
}
if(name && array && isAValidType)
{
ConvertedString += name + ':::' + type + '|***|';
switch(type)
{
case 'ARRAY':
for(var i=0;i<array.length;i++)
{
if(i>0){ConvertedString += '~~~';}
ConvertedString += array[i];
}
break;
case 'DICT':
var firstTime = true;
for(var key in array)
{
if(!firstTime){ConvertedString += '~~~';}
ConvertedString += key + '^^^' + array[key];
firstTime=false;
}
break;
}
}
else
{
SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
}
return ConvertedString;
}
//deletes a current data array
function deleteArrayByName(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var br = '<br />';
var isSaved = false;
if(name)
{
var delidx = getIndexOf(name);
if(delidx > -1)
{
var datstr = '';
var data = loadFile('KeepSheetNames').split('|###|');//Array Data String two different forms possible
for(var i=0;i<data.length;i++)
{
if(delidx !== i)
{
if(i>0){datstr += '|###|';}
datstr += data[i];
}
}
isSaved=saveFile(datstr);
}
return isSaved;
}
}
function dispFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var file = loadFile();
if(file)
{
dispStatus('Displaying File: ' + filename, file, 800, 500);
}
else
{
SpreadsheetApp.getUi().alert('File "' + filename + '" not found in function dispFile.');
}
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
function delFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID)
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
targetFound = true;
fldr.removeFile(fi);
SpreadsheetApp.getUi().alert('File: ' + filename + ' was removed from: ' + fldr.getName() + '/' + target);
}
}
return targetFound;
}
function saveFile(datstr,filename)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
targetFound = true;
fi.setContent(datstr);
}
return targetFound;
}
}
Utility.gs
// Display a modeless dialog box with custom HtmlService content.
function dispStatus(title,html,width,height,modal)
{
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 400;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var modal = typeof(modal) !== 'undefined' ? modal : false;
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
if(!modal)
{
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
else
{
SpreadsheetApp.getUi().showModalDialog(htmlOutput, title);
}
}
You will have to setup a onEdit trigger to call KeepSheetNames() and that should do it. I played with it a bit and it seems to work okay. If you find anything wrong with feel free to fix it. Also you'll have to add the id of your data folder. I decided that it probably wasn't a good idea to publish that.
Related
I am using a script to show me new files in google drive so people can see that a file has been updated. The script worked fine with one or two users using the system but after migrating a few more we started getting errors about exceeding maximum execution time. Currently the script deletes the current list and recreates it each and every hour
function listFilesInFolder() {
//try {
// If you want a tree of any sub folder
//var parent = DriveApp.getFoldersByName("FOLDER_NAME").next();
// If you want to search from the top (root) folder
var files = DriveApp.getFiles();
var ss = SpreadsheetApp.openById("1XbAaoNTiRXKSUAovY-QUvnc8V2q68g7Q3z4NIH_ioTc");
var sheet = ss.getSheetByName("Sheet1");
var file,folder,folders,folderTop,newFiles,lastUpdated,difference;
var j = 0;
var data = []
var parentFolders = []
var newDate = new Date();
while (files.hasNext()) {
file = files.next();
lastUpdated = file.getLastUpdated();
difference = newDate.getTime() - lastUpdated.getTime();
if ((difference/86400000) < 100) {
folders = file.getParents();
while (folders.hasNext()) {
folder = folders.next();
folders = folder.getParents();
parentFolders.push(folder.getName())
}
folderTop = parentFolders[parentFolders.length -2]
data.push (new Array());
data[j].push(file.getName());
data[j].push(file.getLastUpdated());
data[j].push("open_in_new");
data[j].push("https://drive.google.com/file/d/"+file.getId()+"/edit");
data[j].push("folder_open");
if (file.getParents().hasNext())
{
data[j].push("https://drive.google.com/drive/u/0/folders/" + file.getParents().next().getId());
}
else
{
data[j].push("https://drive.google.com/drive/");
}
data[j].push(folderTop+"#xxx.net");
j = j+1;
}
}
sheet.deleteRows(2, sheet.getMaxRows()-1)
sheet.deleteColumns(2, sheet.getMaxColumns()-1)
sheet.clear()
sheet.appendRow(["File Name","Date Updated","View File","File Link", "Open Folder","Folder Link", "Cell" ]);
sheet.appendRow(["","","HyperlinkType(D)-iconType","", "HyperlinkType(F)-iconType","", "Permissions-Hidden"] );
var destinationRange = sheet.getRange(3, 1,j , 7);
destinationRange.setValues(data);
}
// catch (e) {
// Logger.log(e.toString());
// }
// }
function getFilesFromFolder(parent,targetSheet,topLevelName) {
var files = parent.getFiles();
var data
var file
while (files.hasNext()) {
file =files.next()
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
file.getDescription(),
file.getLastUpdated(),
file.getMimeType(),
topLevelName+"#xxx.net"
];
targetSheet.appendRow(data);
row.push([file.getId(),
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
file.getDescription(),
file.getLastUpdated(),
file.getMimeType()
]);
}
}
function getChildFolders(parent,targetSheet,topLevelName) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
getFilesFromFolder(childFolder,targetSheet,topLevelName);
getChildFolders(childFolder,targetSheet,topLevelName);
}
// Recursive call for any sub-folders
}
Thank you.
Here's a script that uses DriveActivity API to monitor changes to Google Drive. The Qwikstart is here and I took that script and modified it.
I hardwired the timezone into the query filter so you'll need to address that and there's also the variable n and nl that I used to limit the number of calls so that I would hit quota limits during development.
It generates the html for the results and displays everything in a dialog.
Code.gs:
/**
* Lists activity for a Drive user.
*/
function listDriveActivity() {
const dt=new Date();
const dt0=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-1);
const dt1=Utilities.formatDate(dt0, Session.getScriptTimeZone(),"yyyy-MM-dd");
const dt2=Utilities.formatDate(dt0, Session.getScriptTimeZone(), "HH:mm:ss")
const dt3=dt1+"T"+dt2+"-07:00";
const dt4=Utilities.formatDate(new Date(dt3), Session.getScriptTimeZone(), "E MM/dd/yyyy HH:mm:ss")
var html='Recent Activities ' + dt4 + ' ' + Session.getScriptTimeZone();
html+='<style>td,th{padding:2px;border:1px solid black;overflow-wrap: break-word;\} table{table-layout:fixed;width:100%;}</style>';
html+='<table>';
html+='<tbody>';
html+='<tr><th>Time</th><th>Actors</th><th>Actions</th><th>Targets</th></tr>';
var token="";
var n=0;
var nl=10;//I needed to reduce the number of calls to not exceed quota during development
do{
var request = {pageSize: 10,filter:Utilities.formatString('time>=\"%s\"',dt3)};
var response = DriveActivity.Activity.query(request);
var activities = response.activities;
if (activities && activities.length > 0) {
for (var i = 0; i < activities.length; i++) {
var activity = activities[i];
var time = getTimeInfo(activity);
var actions = getActionInfo(activity.actions);
var actors = activity.actors.map(getActorInfo);
var targets = getTargetInfo(activity.targets);
//html+=Utilities.formatString('<tr><td style="width:15%;">%s</td><td style="width:15%;">%s</td><td style="width:25%;">%s</td><td style="width:35%;">%s</td></tr>',time,truncated(actors),actions,targets);
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',time,actors,actions,targets);
Logger.log(JSON.stringify(activities[i]));
if(++n > nl)break;;
}
} else {
html+='<br />No Further Activity';
}
token=response.nextPageToken;
}while(token!='' && n<=nl);
html+='</tbody></table><br />n=' + n;
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html).setWidth(1200), "Drive Activity")
}
/** Returns a string representation of the first elements in a list. */
function truncated(array, opt_limit) {
var limit = opt_limit || 2;
var contents = array.slice(0, limit).join(', ');
var more = array.length > limit ? ', ...' : '';
return '[' + contents + more + ']';
}
/** Returns the name of a set property in an object, or else "unknown". */
function getOneOf(object) {
for (var key in object) {
return key;
}
return 'unknown';
}
function getTimeInfo(activity) {
if ('timestamp' in activity) {
const dt=new Date(activity.timestamp);
return Utilities.formatDate(dt, Session.getScriptTimeZone(), "E MM/dd/yyyy HH:mm:ss") + '<br />' + activity.timestamp;
}
return 'unknown';
}
function getActionInfo(acts) {
let html='';
acts.forEach(function(d,i){
if(i>0)html+='<br /><br />';
html+=JSON.stringify(d)
});
return html;
}
/** Returns user information, or the type of user if not a known user. */
function getUserInfo(user) {
if ('knownUser' in user) {
var knownUser = user.knownUser;
var isMe = knownUser.isCurrentUser || false;
return isMe ? 'people/me' : knownUser.personName;
}
return getOneOf(user);
}
/** Returns actor information, or the type of actor if not a user. */
function getActorInfo(actor) {
if ('user' in actor) {
return getUserInfo(actor.user)
}
return getOneOf(actor);
}
/** Returns the type of a target and an associated title. */
function getTargetInfo(targets) {
let html='';
targets.forEach(function(t,i){
if(i>0)html+='<br /><br />';
//html+=JSON.stringify(t);
html+='target: ' + i;
html+=Utilities.formatString('<br />title: %s, type: %s, personName: %s, domainName: %s, id: %s',t.driveItem.title,t.driveItem.mimeType,getUserInfo(t.driveItem.owner.user),t.driveItem.owner.domain.name,t.driveItem.name.slice(6));
});
return html;
}
I am getting error in line 29. But the same code works when pasted in another sheet. Separate trigger is used. Edit-> Current project's trigger.
var Team_email='abc#gmail.com';
function TriggerOnEdit(e)
{
Logger.log("stg1");
sendEmailOnassigned(e);
}
function showMessageOnApproval(e)
{
var edited_row = checkStatusIsAssigned(e);
if(edited_row > 0)
{
SpreadsheetApp.getUi().alert("Row # "+edited_row+" approved!");
}
}
function showMessageOnUpdate(e)
{
var range = e.range;
SpreadsheetApp.getUi().alert("range updated " + range.getA1Notation());
}
function checkStatusIsAssigned(e)
{
Logger.log("stg3");
var range = e.range;
if(range.getColumn() <= 12 &&
range.getLastColumn() >=12 )
{
var edited_row = range.getRow();
var status = SpreadsheetApp.getActiveSheet().getRange(edited_row,11).getValue();
if(status == 'Assigned')
{
return edited_row;
}
}
return 0;
}
function sendEmailOnassigned(e)
{
Logger.log("stg2");
var approved_row = checkStatusIsAssigned(e);
if(approved_row <= 0)
{
return;
}
Logger.log("stg4");
sendEmailByRow(approved_row);
}
function sendEmailByRow(row)
{
Logger.log("stg5");
var values = SpreadsheetApp.getActiveSheet().getRange(row,1,row,13).getValues();
var row_values = values[0];
var mail = composeAssignedEmail(row_values);
MailApp.sendEmail(Team_email,mail.subject,mail.message);
var Requester_email = composeRequesterEmail(row_values);
MailApp.sendEmail(Requester_email.email,Requester_email.subject,Requester_email.message);
}
function composeAssignedEmail(row_values)
{
Logger.log("stg6");
var Request_Number = row_values[1];
var email = row_values[2];
var Project_Name = row_values[4];
var Nature_Of_Work = row_values[5];
var Quantity = row_values[6];
var Estimated_Hours = row_values[7];
var Name = row_values[12];
var message = "Hello Requester, \n "+" \n The following Resource "+ Name ;
var subject = "Request_Number - " + Request_Number ;
return({message:message,subject:subject});
}
function composeRequesterEmail(row_values)
{
Logger.log("stg7");
var Request_Number = row_values[1];
var email = row_values[2] ;
var Project_Name = row_values[4];
var Nature_Of_Work = row_values[5];
var Quantity = row_values[6];
var Estimated_Hours = row_values[7];
var Name = row_values[12];
var message = "Hello Requester, \n "+" \n The following Resource "+ Name;
var subject = "Request_Number - " + Request_Number;
return({message:message,subject:subject, email:email });
}
Please tell me the error where is the mistake.
We can not use debug function to understand the mistake. because trigger is on edit.
Also when we use 'e' what are the information do we feed the function?
How to correct this?
I would be very appreciative of any input. Thank you;
I'm using the G Suite Developer Quickstart for a Meet attendance script
https://developers.google.com/gsuite/add-ons/editors/sheets/quickstart/attendance
Unfortunately, upon using the provided code, and having made adjustments, I either always get "Absent" or "Present" for all students (regardless of whether they were present or not) depending on if I use "null" of "false" in an if statement for activities for applicationName 'meet'.
Here is the code I'm using as a superuser:
...
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Opciones SG')
.addItem("Importar Curso", 'importCourses')
.addItem('Verificar Asistencia', 'checkAll')
.addToUi();
}
function importCourses() {
var optionalArgs = {
teacherId: 'me',
pageSize: 5
};
var response = Classroom.Courses.list();
var courses = response.courses;
for (var i = 0; i < 1; i++) {
var courseName = courses[i].name;
var courseId = courses[i].id;
insertCourse(courseName, courseId)
}
}
function insertCourse(courseName, courseId) {
var spreadsheetName = courseName + "(" + courseId + ")"
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName(spreadsheetName);
if (yourNewSheet != null) {
return
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName(spreadsheetName);
yourNewSheet.appendRow(['Nombre', 'Email', 'Asistencia'])
yourNewSheet.setFrozenRows(1)
var studentNames = getRoster(courseId)["studentNames"]
var studentEmails = getRoster(courseId)["studentEmails"]
for (var i = 0; i < studentNames.length; i++) {
yourNewSheet.appendRow([studentNames[i],studentEmails[i]])
}
yourNewSheet.autoResizeColumns(1, 2)
yourNewSheet.setFrozenColumns(2)
}
function getRoster(courseId) {
var studentNames = []
var studentEmails = []
var optionalArgs = {
pageSize: 100
};
var response = Classroom.Courses.Students.list(courseId, optionalArgs)
var students = response.students
for (var i = 0; i < 100; i++) {
try {
studentNames.push(students[i].profile.name.fullName)
studentEmails.push(students[i].profile.emailAddress)
} catch (err) {
return { "studentNames":studentNames, "studentEmails":studentEmails }
}
}
}
function checkAll() {
var ss = SpreadsheetApp.getActiveSheet();
var sheet = ss.getDataRange().getValues();
for (var i = 2; i < sheet.length * 100; i++){
var meetCode = getCleanCode(sheet[0][i])
// No Meet code given
if (meetCode == null) {
break;
}
else {
// check whether each student was present in Meet
checkMeet(meetCode, i+1);
}
}
}
function checkMeet(meetCode, index) {
// universal settings - static
var userKey = 'all';
var applicationName = 'meet';
var ss = SpreadsheetApp.getActiveSheet();
var sheet = ss.getDataRange().getValues();
for (var i = 0; i < sheet.length-1; i++) {
var emailAddress = sheet[i+1][1]
var optionalArgs = {
event_name: "call_ended",
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
try {
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
var activities = response.items;
if (activities == false) {
markAbsent(ss,i+2,index)
}
else {
markPresent(ss,i+2,index)
}
} catch (err) {
continue
}
}
}
function getCleanCode(meetCode) {
try{
return meetCode.replace("/-/g","")
} catch (err) { return meetCode; }
}
function markAbsent(sheet, i, j) {
var cell = sheet.getRange(i, j);
cell.setValue("Absent");
}
function markPresent(sheet, i, j) {
var cell = sheet.getRange(i, j);
cell.setValue("Present");
}
...
For the correct functionality of the code, check for if (activities == null) or if (activities == undefined) - NOT if (activities == false)
If there are no response items (that is no items have been found for a given user and meeting code) - activities will be undefined, but not false.
if (activities == false) will never be fulfilled and if you use it - all participants will be marked as present
On the other hand, if activities == undefined for other reasons - for example because you introduced the wrong meet code (don't forget to replace 'Asistencia' through a valid meet code), all participants will be marked as absent
Note that the Reports API has some delay, so do not expect to retrieve participation data in live time.
If all participants are marked as absent - probably the data did not propagate yet, wait some time and try again.
Make sure you pass the correct meet code to the script. Your meet code should look something like xxx-xxxx-xxx.
The script needs to remove the - for correct functionality. For this please change in function getCleanCode(meetCode) the line return meetCode.replace("/-/g","") to return meetCode.replace(/-/g, "");
As for the question in your comment: here you can see all available Hangouts Meet Audit Activity Events that you can use for filtering instead of the meeting_code. Unfortunately the timestamp is not one of possible query parameters.
Here is the code we have been using for a few months now, no glitches:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Asistencia')
.addItem('Asistencia', 'checkAll')
.addItem('*Crear*', 'createNewSheets')
.addToUi();
}
function createNewSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("A:A");
var employeeObjects = employeeDataRange.getValues();
var template = ss.getSheetByName('Template');
for (var i=0; i < employeeObjects.length; i++) {
// Put the sheet you want to create in a variable
var sheet = ss.getSheetByName(employeeObjects[i]);
// Check if the sheet you want to create already exists. If so,
// log this and loop back. If not, create the new sheet.
if (sheet) {
Logger.log("Sheet " + employeeObjects[i] + "already exists");
} else {
template.copyTo(ss).setName(employeeObjects[i]);
}
}
return;
}
function importCourses() {
var optionalArgs = {
teacherId: 'me',
pageSize: 5
};
var response = Classroom.Courses.list(optionalArgs);
var courses = response.courses;
for (var i = 0; i < 2; i++) {
var courseName = courses[i].name;
var courseId = courses[i].id;
insertCourse(courseName, courseId)
}
}
function insertCourse(courseName, courseId) {
var spreadsheetName = courseName + "(" + courseId + ")"
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName(spreadsheetName);
if (yourNewSheet != null) {
return
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName(spreadsheetName);
yourNewSheet.appendRow(['Nombre', 'Email', 'Asistencia'])
yourNewSheet.setFrozenRows(1)
var studentNames = getRoster(courseId)["studentNames"]
var studentEmails = getRoster(courseId)["studentEmails"]
for (var i = 0; i < studentNames.length; i++) {
yourNewSheet.appendRow([studentNames[i],studentEmails[i]])
}
yourNewSheet.autoResizeColumns(1, 2)
yourNewSheet.setFrozenColumns(2)
}
function getRoster(courseId) {
var studentNames = []
var studentEmails = []
var optionalArgs = {
pageSize: 100
};
var response = Classroom.Courses.Students.list(courseId, optionalArgs)
var students = response.students
for (var i = 0; i < 100; i++) {
try {
studentNames.push(students[i].profile.name.fullName)
studentEmails.push(students[i].profile.emailAddress)
} catch (err) {
return { "studentNames":studentNames, "studentEmails":studentEmails }
}
}
}
function checkAll() {
var ss = SpreadsheetApp.getActiveSheet();
var sheet = ss.getDataRange().getValues();
for (var i = 2; i < sheet.length * 100; i++){
var meetCode = getCleanCode(sheet[0][i])
// No Meet code given
if (meetCode == null) {
break;
}
else {
// check whether each student was present in Meet
checkMeet(meetCode, i+1);
}
}
}
function checkMeet(meetCode, index) {
// universal settings - static
var userKey = 'all';
var applicationName = 'meet';
var ss = SpreadsheetApp.getActiveSheet();
var sheet = ss.getDataRange().getValues();
//let today = new Date()
//var staringTime = new Date().toISOString();
// var DateValue = ss.getRange(1, 1).getValues();
for (var i = 0; i < sheet.length-1; i++) {
var emailAddress = sheet[i+1][1]
var optionalArgs = {
startTime: formatStartDate(),
event_name: "call_ended",
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
try {
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
var activities = response.items;
if (activities == undefined) {
markAbsent(ss,i+2,index)
}
else {
markPresent(ss,i+2,index)
}
} catch (err) {
continue
}
}
}
function getCleanCode(meetCode) {
try{
return meetCode.replace(/-/g, "");
} catch (err) { return meetCode; }
}
function markAbsent(sheet, i, j) {
var cell = sheet.getRange(i, j);
cell.setValue("A");
}
function markPresent(sheet, i, j) {
var cell = sheet.getRange(i, j);
cell.setValue("");
}
function formatStartDate(){
let date = new Date();
const offset = date.getTimezoneOffset();
let offsetDate = new Date(date.getTime() - (offset*145*1000));
return offsetDate.toISOString();
}
Actual web page image that should come I am getting error:
"The script completed but did not return anything."
I have published new version of code but still getting the error after saving the code and error which is coming is "The script completed but did not return anything."
Code.gs
function doGet(e) {
var op = e.parameter.action;
var ss = SpreadsheetApp.openByUrl("some url");
var sheet = ss.getSheetByName("Sheet1");
if (op == "insert")
return insert_value(e, sheet);
//Make sure you are sending proper parameters
if (op == "read")
return read_value(e, ss);
if (op == "update")
return update_value(e, sheet);
if (op == "delete")
return delete_value(e, sheet);
}
//Recieve parameter and pass it to function to handle
function insert_value(request, sheet) {
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 1;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var id1 = sheet.getRange(i, 2).getValue();
if (id1 == id) {
flag = 0;
var result = "Id already exist..";
}
}
//add new row with recieved parameter from client
if (flag == 1) {
var d = new Date();
var currentTime = d.toLocaleString();
var rowData = sheet.appendRow([currentTime, id, country]);
var result="Insertion successful";
}
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_value(request, ss) {
var output = ContentService.createTextOutput(),
data = {};
//Note : here sheet is sheet name , don't get confuse with other operation
var sheet = "sheet1";
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
//update function
function update_value(request, sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var flag = 0;
var country = request.parameter.name;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.getRange(i, 3).setValue(country);
var result = "value updated successfully";
flag = 1;
}
}
if (flag == 0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function delete_value(request,sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 0;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.deleteRow(i);
var result = "value deleted successfully";
flag = 1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
HTML script section
<script>
var script_url = "apps script webapp url";
// Make an AJAX call to Google Script
function insert_value() {
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=insert";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function update_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=update";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function delete_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=delete";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
$("#re").html(e.result);
$("#re").css("visibility","visible");
read_value();
}
function read_value() {
// Other code here to process the result
}
</script>
HTML function calls:
<body>
<div align="center">
<h1>Operations .</h1>
<p>This is simple application<p>
<form >
ID
<input type = "text" name ="id" id="id">
Name
<input type = "text" name ="name" id="name">
</form>
<div id="loader"></div>
<p id="re"></p>
<input type = "button" id = "b1" onClick="insert_value()" value = "Insert"></input>
<input type="button" onclick="read_value()" value="Read" />
<input type="button" onclick="update_value()" value="Update" />
<input type="button" onclick="delete_value()" value="Delete" />
<div id="showData"></div>
</div>
</body>
<div align="center">
</div>
<html>
It should show web page for performing operation shown in screenshot
web page:
The error is correct - consider what happens when no parameters are given to your webapp function doGet. This scenario occurs when the webapp is visited via browser. To resolve this error, you must return something:
function doGet(e) {
console.log({event: e});
...
if (op)
return ContentService.createTextOutput("Unsupported operation");
else
return HtmlService.createHtmlOutputFromFile(...);
}
}
The default response will vary based on how your webapp is used - if you intend to use the webapp only as a crud backend vs. if you plan to have it host the web interface as well.
If the webapp is to host the interface as well, your HTML should use the built in client-server communication (google.script.run...) rather than jQuery.ajax. Review the Apps Script documentation in detail. This pattern will allow you to report and even handle errors in your server code execution.
I'm about to bulk update multiple users email domaine in g-suite using the code below - found it here https://support.google.com/a/answer/7068037
// Cell Colors
COLOR_GRAY = '#434343';
COLOR_GREEN = '#B5D5A7';
COLOR_RED = '#E89898';
COLOR_YELLOW = '#FDE398';
COLOR_WHITE = '#FFFFFF';
// Sheet Columns
COLUMN_PARAMETER = 1;
COLUMN_RESULT = 2;
COLUMN_USER = 1;
COLUMN_VALUE = 2;
// Header Labels
HEADER_PARAMETER = 'Parameter';
HEADER_RESULT = 'Result';
HEADER_USER = 'Username';
HEADER_VALUE = 'Value';
// Status Messages
MESSAGE_COMPLETE = 'User renamed to: ';
MESSAGE_PAUSE = 'Select "Start Rename" from the "Actions" menu to continue';
MESSAGE_RUNTIME = 'Runtime exceeded. Will resume automatically in a few minutes';
MESSAGE_STOP = 'Select "Start Rename" from the "Actions" menu to continue';
// Parameter Labels
PARAMETER_DOMAIN = 'Domain Name';
PARAMETER_CURRENT = 'Current Row';
PARAMETER_RUN = 'Run Number';
// Parameter Dimensions
PARAMETER_COLUMNS = 2;
PARAMETER_ROWS = 4;
// Result Dimensions
RESULT_COLUMNS = 2;
// Sheet Rows
ROW_DOMAIN = 2;
ROW_HEADER = 1;
ROW_CURRENT = 4;
ROW_RUN = 3;
// Runtime Settings
RUNTIME_MAX = 270000;
RUNTIME_PAUSE = 60000;
// Sheet Names
SHEET_PARAMETERS = 'Parameters';
SHEET_RESULTS = 'Results';
// Status Labels
STATUS_ABORT = '[ABORTED]';
STATUS_ERROR = '[ERROR]';
STATUS_PAUSE = '[PAUSED]';
STATUS_COMPLETE = '[COMPLETED]';
// Cell Sizes
WIDTH_SMALL = 200;
WIDTH_MEDIUM = 400;
WIDTH_LARGE = 800;
// Parameter Values
VALUE_CURRENT = 2;
VALUE_NULL = '';
VALUE_RUN = 1;
// Clears all triggers from current project.
function clearTriggers() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
// Returns currently active sheet
function getCurrentSheet() {
return SpreadsheetApp.getActiveSheet();
}
// Returns currently active spreadsheet
function getCurrentSpreadsheet() {
return SpreadsheetApp.getActiveSpreadsheet();
}
// Returns value of specified cell in a sheet
function getCellValue(sheet, row, column) {
return sheet.getRange(row, column).getValue();
}
// Returns value of the specified parameter
function getParameter(parameter) {
return getCellValue(getSheet(SHEET_PARAMETERS), parameter, COLUMN_VALUE);
}
// Returns sheet with the specified name (if one exists)
function getSheet(name) {
return getCurrentSpreadsheet().getSheetByName(name);
}
// Returns true if 'haystack' contains 'needle'.
function hasString(haystack, needle) {
return String(haystack).indexOf(needle) != -1;
}
// Returns true if script is nearing the max run time (4.5 min).
function isRuntimeExpired(start, currentTime) {
return currentTime - start >= RUNTIME_MAX;
}
// Adds custom items to "Actions" menu of spreadsheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Actions')
.addItem('Start Rename', 'startRename')
.addItem('Pause Rename', 'pauseRename')
.addItem('Stop Rename', 'stopRename')
.addItem('Reset Spreadsheet', 'resetSpreadsheet')
.addToUi();
}
// Pause rename process (manually)
function pauseRename() {
clearTriggers();
var results = getSheet(SHEET_RESULTS);
var lastRow = results.getLastRow();
var row = getParameter(ROW_CURRENT);
var currentResult = getCellValue(results, row, COLUMN_RESULT);
if (!hasString(currentResult, STATUS_ABORT) &&
!hasString(currentResult, STATUS_ERROR) &&
!hasString(currentResult, STATUS_PAUSE)) {
row = row + 1;
}
if (row < lastRow) {
setResult(row, COLOR_YELLOW, STATUS_PAUSE, MESSAGE_PAUSE);
}
}
// Formats layout of "Parameters" sheet
function formatParameters() {
var parameters = getSheet(SHEET_PARAMETERS);
var lastColumn = parameters.getMaxColumns();
var lastRow = parameters.getMaxRows();
if (lastColumn > PARAMETER_COLUMNS) {
parameters.deleteColumns(
PARAMETER_COLUMNS + 1, lastColumn - PARAMETER_COLUMNS);
}
parameters.getRange(ROW_HEADER, COLUMN_PARAMETER, lastRow).clear();
parameters.getRange(ROW_HEADER, COLUMN_VALUE, lastRow).clear();
parameters.getRange(ROW_HEADER, COLUMN_RESULT).setFontColor(COLOR_WHITE);
parameters.setColumnWidth(COLUMN_PARAMETER, WIDTH_SMALL);
parameters.setColumnWidth(COLUMN_VALUE, WIDTH_SMALL);
parameters.getRange(ROW_HEADER, COLUMN_PARAMETER)
.setBackground(COLOR_GRAY)
.setFontColor(COLOR_WHITE)
.setValue(HEADER_PARAMETER);
parameters.getRange(ROW_HEADER, COLUMN_VALUE)
.setBackground(COLOR_GRAY)
.setFontColor(COLOR_WHITE)
.setValue(HEADER_VALUE);
parameters.getRange(ROW_DOMAIN, COLUMN_PARAMETER).setValue(PARAMETER_DOMAIN);
parameters.getRange(ROW_RUN, COLUMN_PARAMETER).setValue(PARAMETER_RUN);
parameters.getRange(ROW_CURRENT, COLUMN_PARAMETER)
.setValue(PARAMETER_CURRENT);
parameters.setFrozenRows(ROW_HEADER);
}
// Formats layout of "Results" sheet
function formatResults() {
var results = getSheet(SHEET_RESULTS);
var userHeader = results.getRange(ROW_HEADER, COLUMN_USER);
var lastColumn = results.getMaxColumns();
var lastRow = results.getLastRow();
if (hasString(userHeader.getValue(), '#')) {
results.insertRowBefore(1);
}
if (lastColumn > RESULT_COLUMNS) {
results.deleteColumns(RESULT_COLUMNS + 1, lastColumn - RESULT_COLUMNS);
}
if (lastColumn < RESULT_COLUMNS) {
results.insertColumnAfter(COLUMN_USER);
}
results.getRange(ROW_HEADER, COLUMN_USER, lastRow).clearFormat();
results.getRange(ROW_HEADER, COLUMN_RESULT, lastRow).clear();
userHeader.setFontColor(COLOR_WHITE);
results.getRange(ROW_HEADER, COLUMN_RESULT).setFontColor(COLOR_WHITE);
userHeader.setValue(HEADER_USER);
results.setColumnWidth(COLUMN_USER, WIDTH_MEDIUM);
results.setColumnWidth(COLUMN_RESULT, WIDTH_LARGE);
results.setFrozenRows(ROW_HEADER);
setResult(ROW_HEADER, COLOR_GRAY, HEADER_RESULT, '');
}
// Renames email address of each user in "Results" sheet
function renameUsers(start) {
var results = getSheet(SHEET_RESULTS);
SpreadsheetApp.setActiveSheet(results);
var lastRow = results.getLastRow();
var firstRow = getParameter(ROW_CURRENT);
var domain = getParameter(ROW_DOMAIN);
if (firstRow && firstRow <= lastRow) {
setResult(firstRow, COLOR_WHITE, VALUE_NULL, VALUE_NULL);
for (var row = firstRow; row <= lastRow; row++) {
setCurrentRow(row);
var currentEmail = getCellValue(results, row, COLUMN_USER);
var currentResult = getCellValue(results, row, COLUMN_RESULT);
var userExists = false;
if (row != lastRow) {
if (isRuntimeExpired(start, new Date().getTime())) {
setTrigger(RUNTIME_PAUSE);
setTrigger(RUNTIME_PAUSE + RUNTIME_MAX);
setResult(row, COLOR_YELLOW, STATUS_PAUSE, MESSAGE_RUNTIME);
return;
}
}
if (hasString(currentResult, STATUS_PAUSE)) {
return;
}
if (hasString(currentResult, STATUS_ABORT)) {
var parameters = getSheet(SHEET_PARAMETERS);
setCurrentRow(row);
getCurrentSpreadsheet().deleteSheet(parameters);
return;
}
if (hasString(currentResult, STATUS_COMPLETE)) continue;
setResult(row, COLOR_RED, STATUS_ABORT, VALUE_NULL);
if (!hasString(currentEmail, '#')) continue;
var delimiter = currentEmail.indexOf('#');
var currentUsername = currentEmail.substring(0, delimiter);
var newUsername = currentUsername + '#' + domain;
var user = {'primaryEmail': newUsername};
try {
AdminDirectory.Users.update(user, currentEmail);
message = MESSAGE_COMPLETE + user.primaryEmail;
setResult(row, COLOR_GREEN, STATUS_COMPLETE, message);
} catch (err) {
setResult(row, COLOR_RED, STATUS_ERROR, err.message);
}
Utilities.sleep(100);
parameters = getSheet(SHEET_PARAMETERS);
}
}
getCurrentSpreadsheet().deleteSheet(parameters);
return;
}
//Resets layout of "Results" sheet; removes "Parameters" sheet
function resetSpreadsheet() {
clearTriggers();
var parameters = getSheet(SHEET_PARAMETERS);
if (parameters) {
getCurrentSpreadsheet().deleteSheet(parameters);
}
formatResults();
}
//Sets background color of specified cell in a sheet
function setCellColor(sheet, row, column, color) {
sheet.getRange(row, column).setBackground(color);
}
//Sets value of specified cell in a sheet
function setCellValue(sheet, row, column, value) {
sheet.getRange(row, column).setValue(value);
}
//Sets value of "Row Number" parameter
function setCurrentRow(row) {
var parameters = getSheet(SHEET_PARAMETERS);
Utilities.sleep(50);
setCellValue(parameters, ROW_CURRENT, COLUMN_VALUE, row);
Utilities.sleep(50);
}
//Sets value of "Domain Name" parameter
function setDomainName(domain) {
var parameters = getSheet(SHEET_PARAMETERS);
setCellValue(parameters, ROW_DOMAIN, COLUMN_VALUE, domain);
}
//Sets result of specified row in "Results" sheet
function setResult(row, color, status, message) {
var results = getSheet(SHEET_RESULTS);
results.getRange(row, COLUMN_USER).setBackground(color);
results.getRange(row, COLUMN_RESULT).setBackground(color);
if (message == VALUE_NULL) {
results.getRange(row, COLUMN_RESULT).setValue(status);
} else {
results.getRange(row, COLUMN_RESULT).setValue(status + ' ' + message);
}
}
//Sets value of "Run Number" parameter
function setRunNumber(count) {
var parameters = getSheet(SHEET_PARAMETERS);
setCellValue(parameters, ROW_RUN, COLUMN_VALUE, count);
}
function setTrigger(pause) {
ScriptApp.newTrigger('startRename').timeBased().after(pause).create();
}
//Starts rename process
function startRename() {
clearTriggers();
var start = new Date().getTime();
if (getSheet(SHEET_PARAMETERS)) {
var results = getSheet(SHEET_RESULTS);
var parameters = getSheet(SHEET_PARAMETERS);
setRunNumber(getParameter(ROW_RUN) + 1);
} else {
getCurrentSheet().setName(SHEET_RESULTS);
formatResults();
var domains = AdminDirectory.Domains.list('my_customer').domains;
var ui = SpreadsheetApp.getUi();
var input = ui.prompt('Rename users to which domain?', ui.ButtonSet.OK_CANCEL);
if (input.getSelectedButton() == ui.Button.OK) {
var valid = false;
var domain = input.getResponseText().toLowerCase();
for (var i in domains) {
if (domain == domains[i].domainName.toLowerCase()) {
valid = true;
}
}
if (!valid) {
ui.alert(
'The specified domain is invalid! Please try again.',
ui.ButtonSet.OK);
return;
}
} else {
return;
}
var results = getSheet(SHEET_RESULTS);
var parameters = getCurrentSpreadsheet().insertSheet(SHEET_PARAMETERS);
formatParameters();
setDomainName(domain);
setCurrentRow(VALUE_CURRENT);
setRunNumber(VALUE_RUN);
}
renameUsers(start);
}
//Stop rename process
function stopRename() {
clearTriggers();
var results = getSheet(SHEET_RESULTS);
var lastRow = results.getLastRow();
var row = getParameter(ROW_CURRENT);
var currentResult = getCellValue(results, row, COLUMN_RESULT);
if (hasString(currentResult, STATUS_ABORT) ||
hasString(currentResult, STATUS_ERROR) ||
hasString(currentResult, STATUS_PAUSE)) {
var parameters = getSheet(SHEET_PARAMETERS);
if (parameters) {
getCurrentSpreadsheet().deleteSheet(parameters);
}
} else {
row = row + 1;
}
setResult(row, COLOR_RED, STATUS_ABORT, MESSAGE_STOP);
}
Since I'm changing the domain I will like also to update different fields, like Department....
Is there a simplest way to do it rather then using a script?
Where do I find the users fields?
Regards
Hugo L
I wrote a script for managing G suite user email signatures which you might want to check out.
python set-signatures.py
It allows you to set the signature for every user in your organization using an HTML template, a CSV of users and the Google Service Account API.