If column has value do ______ - google-apps-script

How to search a column on a sheet for a value, and if the value is there continue code? I am trying to make an update system to check to see if their email is on a sheet. If their email is on a sheet then it will check if their system version is up to date. If the system is not to up to date it will then copy their data, delete their current sheet, create a copy from an example then put in their data. If the user does not have the system it will create one for them. It seems to continuously skip Checking their email.
My code uses URLs and IDs but I have taken them out for obvious reasons. Below is an example of the beginning of my code.
function readlog()
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
//do something
}
Here is a full version of my code:
function readlog(){
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var timezone= "CST";
var date = Utilities.formatDate(new Date(),timezone, "E MMM dd,yyyy HH:mm:ss");
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
var container = DriveApp.getFoldersByName('Reading Log')
var fid = DriveApp.getFoldersByName('Reading Log').getId()
var version = sheet.getRange('8th grade!a1')
var update = container.getDescription();
if (update == version) {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('You already have a reading log, and you have the most recent update!', ui.ButtonSet.OK);
} else {
var contents = container.getFiles();
var files = DriveApp.getFolderById(fid).searchFiles(
'title contains "Reading log"');
while (files.hasNext()) {
var file = files.next();
var logtoupdate = file.getUrl;
}
var ss = SpreadsheetApp.openByUrl(logtoupdate);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var logrange = sheet.getRange('8th Grade!e5:o').getValues()
SpreadsheetApp.getActiveSpreadsheet().deleteActiveSheet();
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",container);
var target = read.getRange('8th Grade e5:o').setValues(logrange);
var range = sheet.getRange("A1:B2");
range.setValues([[50, 100]]);
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
}
} else {
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var targetFolder = DriveApp.createFolder("Reading Log");
var eighth = DriveApp.getFileById(URL_);
var share = eighth.makeCopy("(Name): 8th Grade Reading Log",targetFolder);
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",targetFolder);
var folder = sheet.getRange('8th grade!a1');
targetFolder.setDescription(folder);
var idsheet = read.getUrl();
var idshare = share.getUrl();
var idfolder = targetFolder.getUrl()
sheet.appendRow([user,email,date,idfolder,idsheet,idshare]);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Your Reading log is created. There is now a folder in your google drive called Reading log. Have Fun Reading!', ui.ButtonSet.OK);
}
}

Short answer
Instead of email == active use active.join('|').split('|').indexOf(email)
Explanation
getValues() return a two dimensional array.
join('|') convert this array into an string using | as separator.
split('|') convert the above string into an (one dimension) array.
indexOf(email) returns the index of the email value on the above array. If the email value is not found, -1 is returned.
On a comparison -1 is parsed as false.

Related

How to compare values from a google sheets column to an array and send to specific emails based on column data

I'm automating my google sheets to send out emails automatically and I can't figure out how to compare a variable array to a column in my google sheets. I keep getting all values returned rather than just the ones in my array when I put it in an 'IF' statement.
I want my code to only show data that is in my gEnglish variable but instead shows me all data. I was also wondering how I'd be able to send emails based on regions to users.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Main").activate();
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var decisionOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(1,1).getValue();
var decisionTWO = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(2,1).getValue();
var decisionThree = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(3,1).getValue();
var decisionFour = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(5,1).getValue();
var decisionFive = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(4,1).getValue();
var gEnglish = ["IT","US","GB","UK"];
var gSpanish = ["SP"];
var user1 = ["JP","SK","IND","RU"];
var user2 = [gEnglish,"UK"];
var user3 = [gSpanish, "BR", "PT"];
var user4 = ["FR", "DE","IT"];
for (var i = 2;i<=lr;i++){
var type = ss.getRange(i,6).getValue();
var region = ss.getRange(i, 5).getValue();
var decision = ss.getRange(i,15).getValue();
//I used to have if(region == gEnglish)
if(gEnglish.includes(region[i]) ){
var channel = ss.getRange(i,3).getValue();
var decision = ss.getRange(i,15).getValue();
var url = ss.getRange(i, 9).getValue();
var name = ss.getRange(i,11).getValue();
var messageBody = {};
var subjectLine = "blahblahblah";
}
}
}
If my array only has one value inside it works fine but as soon as I put more I just get all values returned.
What am I doing wrong?
Putting a column into a flat array.
function col2array() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const vA=sh.getRange(1,1,sh.getLastRow(),1).getValues().flat();
}
In Google Apps Script a column looks like:
[[Row1],[Row2],[Row3],[Row4]....]
function lookingforarrayvaluesinacolumn() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const vA=sh.getRange(1,1,sh.getLastRow(),1).getValues();
const coolpeople = ["p1","p2"];
vA.forEach(function(r,i){
if(coolpeople.indexOf(r[0])!=-1) {
//the r[0] is a cool person
}
});
}

Add the time when one google sheets document is modified to another sheets document

I have one sheet for a group of people. I'm trying to make a script so that whenever they edit the sheet, the time that they last edited will show up in a sheet in another document.
A sample row from the group sheet looks like this:
col1|...|col10|person name|...|col17
and the sheet that the time should be going to looks like this:
person name|col2|...|col10|date last edited.
this is the code that I've been trying and it is not working so far:
function onEdit(e) {
var row = e.range.getRow();
var col = e.range.getColumn();
var time = new Date().toLocaleString("en-US", {timeZone: "America/Toronto"})
var ID = "sheet ID"; //The ID for the second sheet goes here
var sheet = SpreadsheetApp.OpenById(ID);
var target = sheet.getSheetByName("Sheet2");
var lastColumn = target.getLastColumn();
var lastRow = target.getLastRow();
var range = target.getRange(1,1,lastRow, lastColumn);
var data = range.getValues();
var userEmail = e.user.getEmail();
var array = userEmail.split(".");
var firstName = array[0];
var secondSheet = e.source.getActiveSheet();
var lastRowSecond = secondSheet.getLastRow();
var lastColumnSecond = secondSheet.getLastColumn();
var secondRange = secondSheet.getRange(1,1,lastRowSecond, lastColumnSecond);
var secondData = secondRange.getValues();
var nameRow = secondData[row-1];
var nameColumn = nameRow[10];
var secondPersonarray = nameColumn.split(" ");
var secondPersonFirstName = secondPersonarray[0];
for (var i=1; i<lastRow; i++) {
var sheetRow = data[i];
var name = sheetRow[0].split(" ");
var firstNameSheet = name[0];
if ((firstName == firstNameSheet) && (firstName == secondPersonFirstName)) {
target.getRange(sheetRow, 10).setValue(time);
}
}
}
I've done something similar, only with one document, so I know the problem isn't with the time.

Copy/paste values and formats while asking for name

I am trying to copy over all of the values and formats to a different spreadsheet, week by week, creating a new sheet within the workbook each time. This is for archival purposes. I have pieced together the following:
function ArchiveByWeek(){
var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('CRS Stats By Week')
var buildVersion = Browser.inputBox("What is the Weekend Ending Date?");
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('1WVfJGDbdOewO2H-aMhQiek7sCOolK6xH7cSbfZ8KQgY');
var destinationSheet = destination.insertSheet(buildVersion, 1);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
This seems to work fine, only some cells are not copied. For some reason, it is only cells that are summing other cells. Can't figure out why.
I found the following script, which worked perfectly, only I was unable to find a way to give each new sheet a unique name:
function copySheetValues(){
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
var destinationSheet = destination.insertSheet(sourcename, 0);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
I was actually able to come up with a solution that I was satisfied with. This was able to paste all of the values, and formats exactly as they were on the sheet when viewing. It asks for a name of the new sheet, which was my intention:
function Archive() {
var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET NAME')
var sValues = source.getDataRange()
.getValues();
var weekEnding = Browser.inputBox("What is the Weekend Ending Date?");
var destination = SpreadsheetApp.openById('SHEET ID');
var copy = source.copyTo(destination)
.setName(weekEnding)
copy.getRange(1, 1, sValues.length, sValues[0].length)
.setValues(sValues); // overwrite all formulas that the copyTo preserved

Copy rows from one sheet to another

I need to create a master sheet for our managers that only include activity happening in their areas (I have a script for this that does what I need). These sheets are populated from my master sheet (and are not in the same workbook).
I need to have rows copy to the applicable sheet when there is a new submission. My code below dumps them all to one sheet and I'm not sure why. I'm assuming I don't have the right condition but how do you say "move rows to this sheet when it's this manager"? I thought calling the sheet ID by row would be enough, but I guess not.
Would I then have to do an if else statement for every manager? That will get tedious since I have about 80 managers.
Below is my current code. Any help or advice is appreciated!
function moveRows(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Form Responses 1");
var data = sh.getDataRange().getValues();
// Grab the Headers
var headers = sh.getRange(1,1,1,sh.getLastColumn()).getValues();
var nameCol = headers[0].indexOf('Enter Your Name');
var candCol = headers[0].indexOf('Choose Candidate');
var typeCol = headers[0].indexOf('Merged Experience');
var docCol = headers[0].indexOf('Document Link');
var timeCol = headers[0].indexOf('Timestamp');
var subjectCol = headers[0].indexOf('Choose the Content Area');
var ratingsCol = headers[0].indexOf('Ratings Summary');
var accessCol = headers[0].indexOf('Access');
var activityCol = headers[0].indexOf('Copied to Activity Sheet');
var masterCol = headers[0].indexOf('Master Activity Sheet');
var target = [];
// Loop over the values line by line
for (var i = 0; i < data.length; i++) {
var row = data[i];
var name = row[nameCol];
var activity = row[activityCol];
var master = row[masterCol];
var candidate = row[candCol];
var type = row[typeCol];
var subject = row[subjectCol];
var ratings = row[ratingsCol];
var access = row[accessCol];
var guide = row[docCol];
var time = row[timeCol];
if (activity == "") { // if condition is true copy the whole row to target
target.push([time,name,candidate,subject,type,guide,ratings]);
Logger.log(target);
var ss2 = SpreadsheetApp.openById(master);
var sh2 = ss2.getSheetByName("Sheet1");
sh2.getDataRange().offset(sh2.getLastRow(), 0, target.length, target[0].length).setValues(target);
}
}
}
Note: I have a bunch of different scripts that move rows from one tab to another, but I couldn't find anything where I move it across multiple workbooks.
What you can do is to have an array with for each manager the sheet where to copy the data.
var managerSheet = {
"manager1":"SheetAzerty",
"manager2":"SheetQwerty"
};
to select the sheet just do :
var manager = "manager1"; //This is the value you retrieve
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(managerSheet[manager]);
Stéphane

Copy value and format from a sheet to a new google Spreadsheet document?

I need to copy a sheet on google SpreadSheet to another SpreadSheet document.
I´ve done my research, and I found two methods that do this, however both have problems that I don´t know how to fix.
The first method copies the sheet with format, but it keeps the referenced cells, so I get a reference error in the new document (#ref). I need a function that copies the format and the values (not references).
function copySheet() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var destination = SpreadsheetApp.openById("15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ");
sheet.copyTo(destination);
}
This second method copies the values without references, however it copies only values, without format.
function copySheetValues()
{
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sourceDataRange = source.getDataRange();
var sourceSheetValues = sourceDataRange.getValues();
var sourceRows = sourceDataRange.getNumRows();
var sourceColumns = sourceDataRange.getNumColumns();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
destination.insertSheet(sourcename, 0);
destination.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceSheetValues);
}
How do I write a function that keeps the format and copies the values?
Since you seem to know how to get and set values using the whole data range, just use the other methods to get and set all the other parameters.
The script editor autocomplete is a great help in this case to try not to forget one !
I hope the list is complete, it is a bit of a pain to write though !.
code below, if one of them is not useful to you just delete it (in both directions (set and get).
function copySheetValues(){
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
var destinationSheet = destination.insertSheet(sourcename, 0);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
Edit :
Bryan's answer and your comment made me think of another solution, much more simple and that handles merged cells as well. Here is the code :
function copySheetValuesV2(){
var source = SpreadsheetApp.getActiveSheet();
var sourceName = source.getSheetName();
var sValues = source.getDataRange().getValues();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
source.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceName)
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved
}
In both script be sure that the destination sheet name does not already exist. I didn't handle that case although it is quite easy to do with a try/catch structure.
Another route to try that I think Serge was alluding to here.
function myFunction() {
var source = SpreadsheetApp.openById('SOURCE_ID');
var sourceSheet = source.getSheetByName('Sheet1');
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var tempSheet = source.getSheetByName('temp');
var tempRange = tempSheet.getRange('A1');
var destination = SpreadsheetApp.openById('DEST_ID');
sourceRange.copyTo(tempRange); // paste all formats?, broken references
tempRange.offset(0, 0, sourceValues.length, sourceValues[0].length)
.setValues(sourceValues); // paste all values (over broken refs)
tempSheet.copyTo(destination); // now copy temp sheet to another ss
}
This is a variation upon Sergei's answer.
This script will copy all visible sheets and export them in to a new spreadsheet with " Final" appended to the document title.
function copySheetValuesV4(){
var sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheets = sourceSpreadsheet.getSheets();
var destination = SpreadsheetApp.create(sourceSpreadsheet.getName()+' Final');
for (var i = 0; i < sourceSheets.length; i++){
var sourceSheet = sourceSheets[i];
if (!sourceSheet.isSheetHidden()) {
var sourceSheetName = sourceSheet.getSheetName();
var sValues = sourceSheet.getDataRange().getValues();
sourceSheet.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceSheetName).setName(sourceSheetName);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved */
}
destination.getSheetByName("sheet1").hideSheet() // Remove the default "sheet1" */
}
}