if else statement won't pick up empty cell vs. cell with value - javascript

function gamEmail(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var first = sheet.getRange(lastRow, getColIndexByName("First Name")).getValues()[0];
var nickName = sheet.getRange(lastRow, getColIndexByName("Preferred Name")).getValues()[0];
if (nickName.isBlank() == true)
{var name = first;}
else
{name = nickName;}
var last = sheet.getRange(lastRow, getColIndexByName("Last Name")).getValues()[0];
var mobile = sheet.getRange(lastRow, getColIndexByName("Mobile Phone")).getValues()[0];
var office = sheet.getRange(lastRow, getColIndexByName("Office")).getValues()[0];
var subject = "**GAM New User**" + " " + name + " " + last;
this script sets up a GAM command line for new users, the name variable needs to be the new users first name unless they have a nickName. Then I need to set the name variable to nickName. I can't seem to find an answer. Any suggestions? thanks in advance.

Related

How do I get google Script to recognize a date in a cell?

I've set up an email automation script and its working fine but I'd like for the script to send an email when it recognized that a date (dd/mm/yy) has been entered into a cell. Right now, it's just recognizing when a cell has been filled.
function findTextsendupdate(e){
const sh=e.range.getSheet();
if(sh.getName()=="My Email Sheet" && e.range.columnStart==13") {
const row=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
var Name = row[1];
var job = row[2];
var model = row[4];
var info = "Job number: " + job + "\n";
var emailAddress = row[0];
var isEmailSent = row[14];
var date = row[19]
var toString = Object.prototype.toString;
toString.call["object Date"]
if (isEmailSent != "EmailSent" && date == toString) {
var message = "Dear " + Name + "\n";
var body = info + "\n" + message;
var subject = "email";
MailApp.sendEmail(emailAddress, subject, body);
sh.getRange(e.range.rowStart,14).setValue('EmailSent');
} }}
A good way to do this is to use Regular Expressions. Here is an example that will recognize any date in the format D-M-YY, DD-MM-YYYY, D/M/YY, and DD/MM/YYYY.
let dateFromCell1 = "12/12/90";
let dateFromCell2 = "2/2/2000";
let dateFromCell3 = "asd12/12/90";
let dateFromCell4 = "235";
let dateFromCell5 = "Rome";
let dateRegEx = /^\d{1,2}[-/]\d{1,2}[-/](\d{2}|\d{4})$/;
console.log(dateRegEx.test(dateFromCell1));
//true
console.log(dateRegEx.test(dateFromCell2));
//true
console.log(dateRegEx.test(dateFromCell3));
//false
console.log(dateRegEx.test(dateFromCell4));
//false
console.log(dateRegEx.test(dateFromCell5));
//false

Google Apps Script - Setting a row to complete only after it's been ran through the loop

I have Google Apps Script which inputs events into my google calendar from a spreadsheet. Anyone know how to have the script set a row's background color to green & last column value to "complete" only if it's been ran through the loop?
Currently I have it just setting the full range to these parameters, but would like to prevent certain rows from being included if the last column is equal to "Invalid".
function inputEvents() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("B1").getValue();
var calendar = CalendarApp.getCalendarById(calendarId)
var lr = spreadsheet.getLastRow();
var count = spreadsheet.getRange("A3:AF"+lr+"").getValues();
for (x=0; x<count.length; x++) {
var events = count[x];
var name = events[2];
var phone = events[3];
var email = events[4];
var title = events[5];
var startTime = events[6];
var endTime = events[7];
var description = events[8];
var location = events[9];
var eventId = events[31];
var contactHeader = "CONTACT:";
var descriptionHeader = "DESCRIPTION:";
var complete = "Complete";
var invalid = "Invalid";
var info =
contactHeader.bold() + "\n"
+ name + "\n"
+ phone + "\n"
+ email + "\n"
+ "\n" + descriptionHeader.bold() + "\n"
+ description;
var options = {
'guests' : email,
'description': info,
'sendInvites': 'True',
'location': location,
}
if (eventId != complete && eventId != invalid){
calendar.createEvent(title, startTime, endTime, options);
spreadsheet.getRange("AF3:AF"+lr+"").activate().setValue('Complete');
spreadsheet.getRange("A3:AF"+lr+"").activate().setBackground('#d9ead3');
}
}
}
You're using the setValue and setBackground methods to the entire range, you need to apply them only to the range you're interested in, try setting a currentRow variable and change the range you're getting inside your if statement, like this:
var currentRow = 3 + x;
if (eventId != complete && eventId != invalid){
calendar.createEvent(title, startTime, endTime, options);
spreadsheet.getRange("AF" + currentRow).setValue('Complete');
spreadsheet.getRange("A"+ currentRow + ":AF" + currentRow).setBackground('#d9ead3');
}

Script run only on specific sheet

can you please tell me, how to change code to run script only on specified sheet? I want to send e-mails if some value in 2nd column of specified sheet will change. Currently it is sending e-mails if I change 2nd column in any sheet.
I have tried code below, but didn't work:
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('sheetname'))
This is code I have:
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var mycell = ss.getActiveSelection();
var cellcol = mycell.getColumn();
var row = sheet.getActiveRange().getRow();
var cellvalue = mycell.getValue().toString();
var recipients = "email#email.com";
if (cellcol == 2)
{
var subject = 'Update to '+sheet.getName();
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '»';
MailApp.sendEmail(recipients, subject, body);
}
}
Thank you.

Correct script to send only the last row of data in Google Sheets

The script I have is sending out the information in the format I want. The problem I have is that it is sending out each row as an indiviual email instead of only sending out the latest data. I only want the last row of data to be sent out.
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
lastRow = sheet.getLastRow();
startrow= 2;
var range = sheet.getRange("A2:Z1000");
var UserData = range.getValues();
for (i in UserData) {
var row = UserData[i];
var name = row[2];//market
var senderEmail = ''
if (name === 'South')
{senderEmail = 'tom#no.com';}
else if (name === 'West')
{senderEmail = 'bob#bob.com';}
else if (name === 'East')
{senderEmail = 'non#no.com';}
var AgentOwner = row[18];//Agent Owner
var address = row[20];//Address
var City = row[21];//City
var State = row[22]//state
var Incident = row[17]//incident type
var Date = row[4]//date and time
emailBody = "New Security Incident Report from: " +AgentOwner+ "\nAddress: " +address+ "\nCity: " +City+ "\nState: " +State + "\nIncident: " +Incident + "\nDateTime:" +Date
MailApp.sendEmail(senderEmail,"Security Incident Report", emailBody);
}
}
Try this -
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getRange(sheet.getLastRow(), 1, 1, sheet.getLastColumn())[0];
Logger.log(row);
var name = row[2]; //market
var senderEmail = '';
if (name === 'South') {
senderEmail = 'tom#no.com';
} else if (name === 'West') {
senderEmail = 'bob#bob.com';
} else if (name === 'East') {
senderEmail = 'non#no.com';
}
var AgentOwner = row[18]; //Agent Owner
var address = row[20]; //Address
var City = row[21]; //City
var State = row[22]; //state
var Incident = row[17]; //incident type
var Date = row[4]; //date and time
emailBody =
'New Security Incident Report from: ' +
AgentOwner +
'\nAddress: ' +
address +
'\nCity: ' +
City +
'\nState: ' +
State +
'\nIncident: ' +
Incident +
'\nDateTime:' +
Date;
MailApp.sendEmail(senderEmail, 'Security Incident Report', emailBody);
}
Edit:
Go to script, paste new code, run the function, then in menu, View > Log and see if the row values are logged properly. If any issues with data indices, adjust them accordingly.

Export array of objects into Excel using Javascript

I'm writing a client side method, that creates an array of objects.I open an existing excel to write the values from the array. I get the values using getProperty and store in a variable.
When I try to write those in the excel, I get "event handler failed with message";" ".
Code:
var getItemtoExcel = document.thisItem.newItem("ToExcel", "get");
getItemtoExcel = getItemtoExcel.apply();
var arrToExcel = Array();
for (var j = 0; j < getItemtoExcel.getItemCount(); j++) {
var gotItemForExcel = getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Excel.Workbooks.Open("C:\\test.xls");
var offset = 0;
var row = 2;
for (var c = 0; c < arrToExcel.length; c++) {
var createExcel = arrToExcel[c];
var Number = createExcel.getProperty("nb");
var Type = createExcel.getProperty("type");
var Code = createExcel.getProperty("code");
var State = createExcel.getProperty("state");
Excel.Worksheets("sheet11").Range("A" & row + 1 + offset).Value = Number;
Excel.Worksheets("sheet11").Range("B" & row + 1 + offset).Value = Type;
Excel.Worksheets("sheet11").Range("C" & row + 1 + offset).Value = Code;
Excel.Worksheets("sheet11").Range("D" & row + 1 + offset).Value = State;
row = row + 1;
}
offset = offset + 1;
return this;
document.thisItem.newItem() is from ARASPLM. Its the standard used to call an ItemType(Item) in ARAS
If you have an opportunity to use SheetJS, it's pretty straightforward
Firstly, Install xlsx package npm install --save xlsx
const XLSX = require('xlsx')
// array of objects to save in Excel
let binary_univers = [{'name': 'Hi','value':1},{'name':'Bye','value':0}]
let binaryWS = XLSX.utils.json_to_sheet(binary_univers);
// Create a new Workbook
var wb = XLSX.utils.book_new()
// Name your sheet
XLSX.utils.book_append_sheet(wb, binaryWS, 'Binary values')
// export your excel
XLSX.writeFile(wb, 'Binaire.xlsx');
i think using this you can get what you want but you need to pass the your Object's value with this that i have mentioned here as (Your Data(Object))
window.open('data:application/vnd.ms-excel,' + **(Your Data(Object))**);
here i'm providing simple code for get data into excel format with jquery
SAMPLE DEMO
Thanks for all your suggestions on this question.
I have done with exporting the array into a .csv file successfully.
Here's the code, for others who will need.
var getItemtoExcel=this.newItem("MyForm", "get");
getItemtoExcel=getItemtoExcel.apply();
var arrToExcel = Array();
for (var j=0; j<getItemtoExcel.getItemCount(); j++)
{
var gotItemForExcel=getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\REPORT.csv", true);
var title="Report";
s.WriteLine(title);
var header="Number" + ";" + "Type" + ";" + "Code" + ";" + "Created On" + ";" + "State" + '\n' ;
s.WriteLine(header);
for (var c=0; c<arrToExcel.length; c++){
var createExcel = arrToExcel[c];
var Number =createExcel.getProperty("nb");
var Type=createExcel.getProperty("type");
if(Type===undefined){Type="";}
var Code=createExcel.getProperty("code");
if(Code===undefined){Code="";}
var Date=createExcel.getProperty("created_on");
var State=createExcel.getProperty("created_by_id/#keyed_name");
var value=Number + ";" + Type + ";" + Code + ";" + Date + ";" + State;
s.WriteLine(value);
}
s.Close();
alert("Report Saved as C:\\REPORT.csv");
return this;

Categories

Resources