Related
I have files on the folder and i import them to the google sheet.
I need to add filename to first column before import, but my script add it only to first cell before import
So it gives me:
Filename
Pencil
01/01/2022
Pen
01/02/2022
Hat
And i need
Filename
1/01/2022
Pencil
Filename
1/01/2022
Pen
Filename
01/02/2022
Hat
function Import_Kredo() {
var arr = [];
var files = DriveApp.getFolderById("13kymSiqX0-L6a9ev4It1_BEjH-xM8rnc").getFiles();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Table 1");
copySheet.getRange('A2:G').clear();
while (files.hasNext()) {
var file = files.next();
var mimeType = file.getMimeType();
var ss1 = null, id = null;
if (mimeType == MimeType.MICROSOFT_EXCEL) {
id = Drive.Files.copy({ mimeType: MimeType.GOOGLE_SHEETS }, file.getId()).id;
ss1 = SpreadsheetApp.openById(id);
} else if (mimeType == MimeType.GOOGLE_SHEETS) {
ss1 = SpreadsheetApp.open(file);
}
if (!ss1) continue;
var sheet = ss1.getSheetByName("Table 1");
if (!sheet) continue;
var sheetsRange = sheet.getDataRange();
var sheetsValues = sheetsRange.getValues().filter(r => r[1]).filter(e => e);
var v = sheetsValues.slice(1);
console.log([file.getName(), v])
arr = arr.concat([[file.getName(), ...Array(v[0].length - 1).fill(null)], ...v]);
if (id) DriveApp.getFileById(id).setTrashed(true); // or Drive.Files.remove(id);
}
copySheet.getRange(5, 1, arr.length, arr[0].length).setValues(arr);
}
In your situation, how about the following modification?
From:
arr = arr.concat([[file.getName(), ...Array(v[0].length - 1).fill(null)], ...v]);
To:
var filename = file.getName();
arr = arr.concat(v.map(e => [filename, ...e]));
By this modification, the filename is put into the 1st column of each row.
please refer to the code below:
function getGdriveLinks() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Test');
const fileNames = sheet.getRange('C2:C').getValues();
const mainFolder = DriveApp.getFolderById('Folder ID');
for (var i = 0; i < fileNames.filter(String).length; i++){
var fileName = fileNames[i][0].toString();
var fileLink = getGdriveLink(fileName,mainFolder);
Logger.log(fileLink);
}
}
function getGdriveLink(searchFileName,folder){
var mainFiles = folder.getFiles();
while (mainFiles.hasNext()){
var file = mainFiles.next();
if(file.getName().indexOf(searchFileName) != -1){
Logger.log(file.getUrl());
return file.getUrl();
}
}
var subFolders = folder.getFolders();
while (subFolders.hasNext()){
var subFolder = subFolders.next();
getGdriveLink(searchFileName,subFolder);
}
}
Basically, the aim is to get the filenames in C2:C of Test sheet, find each of these in the 'Folder ID', and then return their URL. The URL is returned correctly when I log it from getGdriveLink(searchFileName,folder) using Logger.log(file.getUrl()). However, it returns null via the Logger.log(fileLink) when the result goes back to getGdriveLinks() function. Is there anything I'm missing? We're using a corporate domain if that's something to consider. Hoping for your guidance. Thanks!
You could also do it this way and avoid recursion altogether
function getPathAllDrivesFromId(fileid) {
var ids = [{id:fileid,name:DriveApp.getFileById(fileid).getName()}];
let r;
do {
r = Drive.Files.get(fileid,{supportsAllDrives:true,supportsTeamDrives:true});
if(r.parents.length > 0) {
//Logger.log(JSON.stringify(r.parents[0]));
ids.push({id:r.parents[0].id,name:DriveApp.getFolderById(r.parents[0].id).getName()});
fileid = r.parents[0].id
}
}while (r.parents.length > 0);
if(ids[ids.length - 1].name == "Drive") {
ids[ids.length - 1].name = Drive.Drives.get(ids[ids.length - 1].id).name;
}
//Logger.log(JSON.stringify(ids));
let path = ids.map(obj => obj.name).flat().reverse().join(' / ')
//Logger.log(path);
return path;
}
function getGdriveLinks() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Test');
const osh = ss.getSheetByName("Results");
const ns = sh.getRange('C2:C' + sh.getLastRow()).getValues();
const folder = DriveApp.getFolderById('Folder ID');
const result = [["Filename", "Id", "Url", "path"]];
ns.forEach(n => {
let files = DriveApp.getFilesByName(n);
while (files.hasNext()) {
let file = files.next();
let path = getPathAllDrivesFromId(file.getId());
if (~path.indexOf(folder.getName())) {
result.push([file.getName(), file.getId(), file.getUrl(), path]);
}
}
})
osh.clearContents();
osh.getRange(1, 1, result.length, result[0].length).setValues(result);
}
As of a couple of weeks now, I'm getting a "Service error: Spreadsheets" error when running a script in Google Sheets. Before that, it was working fine.
It's supposed to export a PDF while deleting some of the empty rows.
I tried adding a 1000ms delay, but that didn't work.
Any help would be greatly appreciated. You can find the code below.
var sheetName = "PDF - B";
var sheetName2 = "Offertes";
var folderID = "XXX"; // Folder id to save in a folder.
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var sourceSheet2 = sourceSpreadsheet.getSheetByName(sheetName2);
var folder = DriveApp.getFolderById(folderID);
var invoiceName = sourceSheet.getRange("B57").getValue();
var invoiceDate = sourceSheet.getRange("H57").getValue();
var invoiceBusnr = sourceSheet.getRange("J1").getValue();
var invoiceDate_2 = Utilities.formatDate(invoiceDate, "CET", "yyyy-MM-dd")
var pdfName = "["+invoiceDate_2+"] "+invoiceName+" - Offerte "+invoiceBusnr+" Ventje";
var fact = sourceSheet.getRange("H60").getValue();
var value_f1 = sourceSheet.getRange("I53").getValue();
var value_f2 = sourceSheet.getRange("I54").getValue();
var buyerRow = sourceSheet.getRange("I61").getValue();
var buyerColumn = sourceSheet.getRange("J61").getValue();
var vColumn = sourceSheet.getRange("G61").getValue();
var f_cell = sourceSheet2.getRange(buyerRow,buyerColumn);
var f_version = sourceSheet2.getRange(buyerRow,vColumn);
if (fact=="F1") {
f_cell.setValue(value_f1);
f_version.setValue(2);
}
if (fact=="F2") {
f_cell.setValue(value_f2);
}
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder));
//repace cell values with text (to avoid broken references)
var destSheet = destSpreadsheet.getSheets()[0]
var destSheet = destSpreadsheet.getSheetByName(sheetName)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
var imageSheet = destSpreadsheet.getSheetByName("Bus foto's");
var imageRow = destSheet.getRange("B1").getValue();
var sourceImage_1 = imageSheet.getRange(imageRow, 2, 1, 1);
var destImage_1 = destSheet.getRange(4, 2, 1, 1);
var sourceImage_2 = imageSheet.getRange(imageRow, 3, 1, 1);
var destImage_2 = destSheet.getRange(4, 7, 1, 1);
var sourceImage_3 = imageSheet.getRange(imageRow, 4, 1, 1);
var destImage_3 = destSheet.getRange(6, 2, 1, 1);
var sourceImage_4 = imageSheet.getRange(imageRow, 5, 1, 1);
var destImage_4 = destSheet.getRange(6, 7, 1, 1);
sourceImage_1.copyTo(destImage_1,SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
sourceImage_2.copyTo(destImage_2,SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
sourceImage_3.copyTo(destImage_3,SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
sourceImage_4.copyTo(destImage_4,SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (i % 10 == 0) { Utilities.sleep(3000); } // Pause the function for 3000 milliseconds after 10 iterations
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
//delete redundant rows
var soverig14 = destSheet.getRange("B50").getValue();
var soverig13 = destSheet.getRange("B49").getValue();
var soverig12 = destSheet.getRange("B48").getValue();
var soverig11 = destSheet.getRange("B47").getValue();
var soverig10 = destSheet.getRange("B46").getValue();
var soverig9 = destSheet.getRange("B45").getValue();
var soverig8 = destSheet.getRange("B44").getValue();
var soverig7 = destSheet.getRange("B43").getValue();
var soverig6 = destSheet.getRange("B42").getValue();
var soverig5 = destSheet.getRange("B41").getValue();
var soverig4 = destSheet.getRange("B40").getValue();
var soverig3 = destSheet.getRange("B39").getValue();
var soverig2 = destSheet.getRange("B38").getValue();
var soverig1 = destSheet.getRange("B37").getValue();
var soverig_t = destSheet.getRange("B36").getValue();
var soverig_m1 = destSheet.getRange("B35").getValue();
var sschuif = destSheet.getRange("B34").getValue();
var boverig3 = destSheet.getRange("B26").getValue();
var boverig2 = destSheet.getRange("B25").getValue();
var boverig1 = destSheet.getRange("B24").getValue();
var boverig0 = destSheet.getRange("B23").getValue();
var boverig_t = destSheet.getRange("B22").getValue();
var boverig_m1 = destSheet.getRange("B21").getValue();
var f1 = destSheet.getRange("B53").getValue();
var f2 = destSheet.getRange("B54").getValue();
var f3 = destSheet.getRange("B60").getValue();
var f4 = destSheet.getRange("B61").getValue();
if (f4=="") {
destSheet.deleteRow(61);
}
if (f3=="") {
destSheet.deleteRow(60);
}
if (f2=="") {
destSheet.deleteRow(54);
}
if (f1=="") {
destSheet.deleteRow(53);
}
if (soverig14=="") {
destSheet.deleteRow(50);
}
if (soverig13=="") {
destSheet.deleteRow(49);
}
if (soverig12=="") {
destSheet.deleteRow(48);
}
if (soverig11=="") {
destSheet.deleteRow(47);
}
if (soverig10=="") {
destSheet.deleteRow(46);
}
if (soverig9=="") {
destSheet.deleteRow(45);
}
if (soverig8=="") {
destSheet.deleteRow(44);
}
if (soverig7=="") {
destSheet.deleteRow(43);
}
if (soverig6=="") {
destSheet.deleteRow(42);
}
if (soverig5=="") {
destSheet.deleteRow(41);
}
if (soverig4=="") {
destSheet.deleteRow(40);
}
if (soverig3=="") {
destSheet.deleteRow(39);
}
if (soverig2=="") {
destSheet.deleteRow(38);
}
if (soverig1=="") {
destSheet.deleteRow(37);
}
if (soverig_t=="") {
destSheet.deleteRow(36);
}
if (soverig_m1=="") {
destSheet.deleteRow(35);
}
if (sschuif=="") {
destSheet.deleteRow(34);
}
if (boverig3=="") {
destSheet.deleteRow(26);
}
if (boverig2=="") {
destSheet.deleteRow(25);
}
if (boverig1=="") {
destSheet.deleteRow(24);
}
if (boverig0=="") {
destSheet.deleteRow(23);
}
if (boverig_t=="") {
destSheet.deleteRow(22);
}
if (boverig_m1=="") {
destSheet.deleteRow(21);
}
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+destSpreadsheet.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to page width, false for actual size
+ '&scale=4' // 1 = Normal 100% -- 2 = Fit to width -- 3 = Fit to height -- 4 = Fit to Page
//+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
// + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
//+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&horizontal_alignment=CENTER' // LEFT/CENTER/RIGHT
//+ '&vertical_alignment=MIDDLE' // TOP/MIDDLE/BOTTOM
// SET ALL MARGINS IN ORDER FOR IT TO WORK
+ '&top_margin=0.4' // set top margin
+ '&bottom_margin=0.4' // set bottom margin
+ '&left_margin=0.7' // set left margin
+ '&right_margin=0.7' // set right margin
+ '&gid='+destSheet.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
// delete pdf if already exists
var files = folder.getFilesByName(pdfName);
while (files.hasNext())
{
files.next().setTrashed(true);
}
// create pdf
var newFile = folder.createFile(theBlob);
// return true;
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
I have also noticed "Service error: Spreadsheets" when trying to create a pdf; this started occurring sometime between 7 April and 28 April.
I have narrowed it down to to a column in my spreadsheet which contains images using the =IMAGE() function. If these are copied using Range.setValues() the "Service error" occurs. This in itself seems to me to be a bug as it's not very informative about what's wrong. It's arguable whether the =IMAGE() should be copyable using setValues()
However, I've discovered it is possible to copy the image formula using Range.setFormulas(), and it's also possible to use Range.setValues() on an image created using menu>insert>image but setValues() does not work if the image is created from a script using SpreadsheetApp.newCellImage()
The last mentioned problem means there is no bypass for scripts to avoid "Service error: spreadsheets" for scripts without some fiddly recoding.
Here's a shared spreadsheet which illustrates the problem: https://docs.google.com/spreadsheets/d/1xJoOf0DJBRUTbaskjKsly3pAGNJ72sT_EV8Tn246Ufo/edit?usp=sharing
"Service error" is also reported on the google issuetracker
Based on the comment of #Tyler2P, I created a workaround, replacing the part from //repace cell values with text with the following code:
var destSheet = destSpreadsheet.getSheets()[0];
var destSheet = destSpreadsheet.getSheetByName(sheetName);
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourceRange1 = sourceSheet.getRange(1,1,3,sourceSheet.getMaxColumns());
var sourceRange2 = sourceSheet.getRange(7,1,(sourceSheet.getMaxRows()-7),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var sourcevalues1 = sourceRange1.getValues();
var sourcevalues2 = sourceRange2.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
var destRange1 = destSheet.getRange(1,1,3,sourceSheet.getMaxColumns());
var destRange2 = destSheet.getRange(7,1,(sourceSheet.getMaxRows()-7),sourceSheet.getMaxColumns());
destRange1.setValues(sourcevalues1);
destRange2.setValues(sourcevalues2);
I'm trying to figure out a script to automate the transfer of data from a column on one sheet, to one of four columns on another sheet. The data being transferred is an order that has been placed, so the data needs to stay in the column its transferred to until it is received. So basically the script needs to find the next blank column and transfer the data there.
For reference, the sheet is HERE:https://docs.google.com/spreadsheets/d/1DxafMMZL7Nc2M4A41Dzssf9dgrzYZgsX1qKgtfhLMlM/edit?usp=sharing. The data that will be transferred is Ordering!P5:P, and will be transferred from there to Pending TOs, either E6:E, F6:F, G6:G or H6:H, based on whether the previous column already has values.
I wrote the following script, but it only worked on the initial test, and fails to detect empty columns F:H. After clearing column E, I could not repeat the initial success.
Any guidance is greatly appreciated.
function PasteTOTEST() {
var ss = SpreadsheetApp.getActive();
const ui = SpreadsheetApp.getUi();
const response = ui.alert('Table is full', ui.ButtonSet.OK);
var copyFrom = ss.getRange('Ordering!P5:P');
var copyTo = ss.setActiveSheet(ss.getSheetByName('Pending TOs'));
var toColumnA = copyTo.getRange('E6:E').activate();
var toColumnB = copyTo.getRange('F6:F').activate();
var toColumnC = copyTo.getRange('G6:G').activate();
var toColumnD = copyTo.getRange('H6:H').activate();
if(ISBLANK(toColumnA)) {
toColumnA;
copyFrom.copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
else if(ISBLANK(toColumnB)) {
toColumnB;
copyFrom.copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
else if(ISBLANK(toColumnC)) {
toColumnC;
copyFrom.copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
else if(ISBLANK(toColumnD)) {
toColumnD;
copyFrom.copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
}
This function will paste the data in the first available column in ranges E6:E, F6:F, G6:G or H6:H
function PasteTOTEST() {
var ss = SpreadsheetApp.getActive();
const ui = SpreadsheetApp.getUi();
const fsh = ss.getSheetByName('Ordering');
const tsh = ss.getSheetByName('Pending TOs');
let frg = fsh.getRange(5, 16, getColHite(16, fsh, ss) - 4, 1);
let ar = availableRanges();
if(ar && ar.length) {
trg = tsh.getRange(6, ar[0]);
frg.copyTo(trg, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
} else {
ui.alert('Table is full', ui.ButtonSet.OK);
}
}
function getColHite(col, sh, ss) {
var ss = ss || SpreadsheetApp.getActive();
var sh = sh || ss.getActiveSheet();
var col = col || sh.getActiveCell().getColumn();
var rcA = [];
if (sh.getLastRow()) { rcA = sh.getRange(1, col, sh.getLastRow(), 1).getValues().flat().reverse(); }
let s = 0;
for (let i = 0; i < rcA.length; i++) {
if (rcA[i].toString().length == 0) {
s++;
} else {
break;
}
}
return rcA.length - s;
}
function clearAllRanges() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Pending TOs');
[...Array.from(Array(4).keys(), x => x + 5)].forEach(n => {
let h = getColHite(n, sh, ss)
if(h>4)sh.getRange(5, n, h - 4, 1).clearContent()
});
}
function availableRanges() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Pending TOs');
let r = [...Array.from(Array(4).keys(), x => x + 5)].reduce((a,v,arr) => {
let h = getColHite(v, sh, ss);
if(h < 6) a.r.push(v);
return a;
},{r:[],availableRanges:function(){return this.r;}}).availableRanges();
//Logger.log(r);
return r;
}
Demo:
In case you are wondering what this does:
[...Array.from(Array(4).keys(), x => x + 5)]
It just feeds the four column numbers into the reduce loop current value
As part of a student attendance system, I would like to add a color stripe to every last row of a class for attendance using App Scripts. My columns of Google Sheets are: (i) Date, (ii) Email, (iii) Latitude, (iv) Longitude, and (v) Subject-code. Tried many ways but did not find the solution.
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = sss.getId();
var sheetName = sss.getName();
var sheet = sss.getSheetByName("TempDataSet");
var sheet1 = sss.insertSheet('TempDataSet_temp');
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
var shID = sheet1.getSheetId().toString();
sheet1.getRange(2, 1, sheet.getLastRow() -1, sheet.getLastColumn()).sort({column: 1, ascending: false});
var columns_delete = [7,2]; //[7,5,4,2];
columns_delete.forEach(col=>sheet1.deleteColumn(col));
//const sss = SpreadsheetApp.getActiveSpreadsheet();
//const sheet = sss.getSheetByName("TempDataSet");
const subs = sheet.getRange('F2:F'+sheet.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet.getRange('A2:A'+sheet.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
var from = Session.getActiveUser().getEmail();
var subject = 'Batch Attendance Record for Your Reference';
var body = 'Dear Student,'+ '\n\n' + 'Greetings! Please find the batch attendance record attached. Stay safe and blessed.' + '\n\n' + 'Thank you.';
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
sss.deleteSheet(sss.getSheetByName('TempDataSet_temp'));
var sheet2 = sss.getSheetByName('StudentList');
var data = sheet2.getLastRow();
var students = [];
var students = sheet2.getRange(2, 6, data).getValues();
//MailApp.sendEmail(students.toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
for (var i=0; i<students.length; i++){ // you are looping through rows and selecting the 1st and only column index
if (students[i][0] !== ''){
MailApp.sendEmail(students[i][0].toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
//MailApp.sendEmail(students[i][0].toString(), subject ,body, {from: from, attachments:[{fileName:"YourAttendaceRecord.xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
}
}
Explanation:
Based on your question, I understand the following steps:
Check if you have at least two unique subjects in column E. One way to do that is to find the unique list of subjects. If the length of that list is 2 or more it means that you have different subjects. In that case, the first block of the if statement evaluates to true and you add a yellow line in the row before the subject is changed.
If you have only one subject, namely the length of the unique list of subjects is 1 the first block of the if statement will evaluate to false. In that case, the script will check whether column A has 2 or more unique dates. If it does, the second block of the if statement will be executed and the script will add a yellow line in the row before the date is changed. Otherwise, it won't do anything.
Solution:
You can execute color() as a standalone script. I would advice you to save this function in a new .gs file and then simply call it within your current script. Namely, put color() anywhere you want in the code snippet you provided.
function color() {
const sss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = sss.getSheetByName("TempDataSet");
const subs = sheet.getRange('E2:E'+sheet.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet.getRange('A2:A'+sheet.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
}
Complete Solution:
function sendEmails(){
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = sss.getId();
var sheetName = sss.getName();
var sheet = sss.getSheetByName("TempDataSet");
var sheet1 = sss.insertSheet('TempDataSet_temp');
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
var shID = sheet1.getSheetId().toString();
sheet1.getRange(2, 1, sheet.getLastRow() -1, sheet.getLastColumn()).sort({column: 1, ascending: true});
var columns_delete = [7,2]; //[7,5,4,2];
columns_delete.forEach(col=>sheet1.deleteColumn(col));
SpreadsheetApp.flush();
const subs = sheet1.getRange('E2:E'+sheet1.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet1.getRange('A2:A'+sheet1.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet1.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet1.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
SpreadsheetApp.flush();
var from = Session.getActiveUser().getEmail();
var subject = 'Batch Attendance Record for Your Reference';
var body = 'Dear Student,'+ '\n\n' + 'Greetings! Please find the batch attendance record attached. Stay safe and blessed.' + '\n\n' + 'Thank you.';
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
sss.deleteSheet(sss.getSheetByName('TempDataSet_temp'));
var sheet2 = sss.getSheetByName('StudentList');
var data = sheet2.getLastRow();
var students = [];
var students = sheet2.getRange(2, 6, data).getValues();
//MailApp.sendEmail(students.toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
for (var i=0; i<students.length; i++){ // you are looping through rows and selecting the 1st and only column index
if (students[i][0] !== ''){
MailApp.sendEmail(students[i][0].toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
//MailApp.sendEmail(students[i][0].toString(), subject ,body, {from: from, attachments:[{fileName:"YourAttendaceRecord.xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
}
}
}