Google script to find if a Cell is blank - isBlank function doesn't work - google-sheets-api

Here is my code. I'm trying to execute the code only if the cell is not blank. As we do not have a inbuilt function for isBlank i though of using it to fill the empty cell with predefined value. But it do
for (var i = 2, k = 2, j = 2, s = 2; i<lastrow && k>0; s++){
var range = sheet.getRange(i,1);
var company = range.getValue();
var range = sheet.getRange(i,2);
var description = range.getValue();
var range = sheet.getRange(i,3);
var priority = range.getValue();
var range = sheet.getRange(i,4);
var urgency = range.getValue();
var range = sheet.getRange(i,5);
var impact = range.getValue();
var range = sheet.getRange(i,6);
var requester = range.getValue();
var range = sheet.getRange(i,7);
var status = range.getValue();
var range = sheet.getRange(i,8);
var subject = range.getValue();
var pay="{\"helpdesk_ticket\":{ \"description\":\""+description+"\", \"subject\":\""+subject+"\",\"email\":\""+requester+"\",\"priority\":\""+priority+"\",\"status\":\""+status+"\",\"impact\":\""+impact+"\", \"urgency\":\""+urgency+"\" }}";
if(description.isBlank()){
var url="https://"+purl+"/helpdesk/tickets.json";
var options = {
"payload": pay,
"method": "POST",
"muteHttpExceptions": true,
Error message:

isBlank() is a method of the class Range. However you are trying to call it on description, which is not an object of the class Range, but one of Number, Boolean, Date, or String as described here

Because you get a value, its not a cell obj anymore, so its a string, and to check if string is 0 we use function length so in your case it should be like
...
if(description.length > 0)
...

Related

Automatically update my Gsheet with an SQL data base

I need to update a file automatically that already has data in it.
The document is filled with an SQL data base thanks to the code below
However, I want it to update itself everyday without deleting any data that are already in the document and only adding new ones (don't want any duplicates).
function readData(db, queryString) {
//connect to the database
var server = 'your-servername-OR-serverPublicIpAddress';
var username = 'your-sql-username';
var password = 'your-password';
var dbUrl = 'jdbc:sqlserver://' + server + ':1433;databaseName=' + db;
var conn = Jdbc.getConnection(dbUrl, username, password );
//query the data
var stmt = conn.createStatement();
var exec_query = stmt.executeQuery(queryString);
var metaData = exec_query.getMetaData();
var numCols = metaData.getColumnCount();
//save query data to an array
var result=[]; //initiate a blank array
//save the column header
header = []; //initiate the header row
for (var col = 0; col < numCols; col++) {
header.push(metaData.getColumnName(col + 1)); //add the name of each column to the header row
};
result.push(header);//after the header row is formed, put it to the result array
//save the data of each row
while (exec_query.next()) {
row_data = [];
for (var col = 0; col < numCols; col++) {
row_data.push(exec_query.getString(col + 1));//add data of each column to the row data
//Logger.log(row_data);
};
result.push(row_data); // add row data to result
//Logger.log(result);
};
exec_query.close();
return result
};
function pushDataToGoogleSheet(data, SheetName) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(SheetName));
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow+1, 1, data.length, data[0].length).setValues(data);
sheet.getDataRange().removeDuplicates();
};
function main() {
db = 'YOUR_DATABASE_NAME'
SQLquery = 'YOUR_SQL_QUERY'
raw_statistics = readData(db, SQLquery); //get raw statistics
pushDataToGoogleSheet(raw_statistics, 'YOUR_SHEET_NAME'); //push to google sheet
};
function main() {
db = 'YOUR_DATABASE_NAME'
SQLquery = 'YOUR_SQL_QUERY'
raw_statistics = readData(db, SQLquery); //get raw statistics
pushDataToGoogleSheet(raw_statistics, 'YOUR_SHEET_NAME'); //push to google sheet
};
However, in the pushDataToGoogleSheet it says that it can't define the length. So, I don't know if I put the right thing for data or not or if there is an issue in my code...
Do you have an idea ?
Thank you for your help !

How to process batchUpdate and copy from one spreadsheet into another using Google Sheets API

Link to original question where I found the below script: How to batch-copy range with Google Sheets Api
Question: How do I modify the below to write into a different spreadsheetId? I've Googled everything I can and can only find examples where the copyPaste occurs within the same SpreadsheetID.
function Test_Copy() {
var spreadsheetId = "1hLXq9zq-tAaGpPtGiY6859h4oKxIbNimxCHPPZOzdE0";
var sheetId = "1792457718";
var sheetIdd = "760382355";
var rangeFrom = Sheets.newGridRange();
rangeFrom.sheetId = sheetId;
rangeFrom.startRowIndex = 0;
rangeFrom.endRowIndex = 23637;
rangeFrom.startColumnIndex = 0;
rangeFrom.endColumnIndex = 23;
var rangeTo = Sheets.newGridRange();
rangeTo.sheetId = sheetIdd;
rangeTo.startRowIndex = 0;
rangeTo.endRowIndex = 23637;
rangeTo.startColumnIndex = 0;
rangeTo.endColumnIndex = 23;
var copyPasteRequest = Sheets.newCopyPasteRequest();
copyPasteRequest.destination = rangeTo;
copyPasteRequest.source = rangeFrom;
copyPasteRequest.pasteType = "PASTE_VALUES";
copyPasteRequest.pasteOrientation = "NORMAL";
var resource = Sheets.newBatchUpdateSpreadsheetRequest();
//Create request object
var request = Sheets.newRequest();
request.copyPaste = copyPasteRequest;
resource.requests = [request];
var res = Sheets.Spreadsheets.batchUpdate(resource , spreadsheetId);
//Logger.log(res.replies);
//Logger.log(res.spreadsheetId);
}

Authentication lost Google app script

I have created a a google app script that create a pdf from a google sheet and send it via email.
I have three script that work perfectly. But with the fourth script (identical to the other)I lost always the authorization after about one - two hours.
Has someone the same problem?
Thanks
Pasquale
Attached code. I use a trigger to lunch code every time the form is submitted.
// When Form Gets submitted
function onFormSubmit(e) {
var docTemplate = "1mI4SQQe4muuW386jgzkxBlZBWuH0OBRdbz1hItOPjK4";
var docName = "DDT";
var ss = SpreadsheetApp.openById("1HzZFDJYAU6H1pptqcA5fEAVelkZw1LP7si9bBrsF_u0")
var sheet = ss.getSheets()[0];
var lastrow = ss.getLastRow();
var d = new Date ();
var id ="0B1-7TPSHWZ1bMlNLTV9tTFJNb2c"; // cartella Raccolta DDT
var folder = DriveApp.getFolderById(id);
//Get information from form and set as variables
//var email = "pasquale.martucci#decathlon.com";
var email = e.values[1];
var mittente = e.values[2];
var destinatario = e.values[3];
var primaQnt = e.values[4];
var primaDescr = e.values[5];
var secondaQnt = e.values[6];
var secondaDescr = e.values[7];
var terzaQnt = e.values[8];
var terzaDescr = e.values[9];
var quartaQnt = e.values[10];
var quartaDescr = e.values[11];
var quintaQnt = e.values[12];
var quintaDescr = e.values[13];
var aspetto = e.values[14];
var colli = e.values[15];
var peso = e.values[16];
var vettore = e.values[17];
// Ricava indirizzi e città
var cell1 = sheet.getRange("S"+lastrow);
cell1.setFormula("=VLOOKUP(C"+lastrow+";Foglio2!A1:C35;2;FALSE)");
var indirMitt = cell1.getValue()
var cell2 = sheet.getRange("T"+lastrow);
cell2.setFormula("=VLOOKUP(C"+lastrow+";Foglio2!A1:C35;3;FALSE)");
var citMitt = cell2.getValue()
var cell3 = sheet.getRange("U"+lastrow);
cell3.setFormula("=VLOOKUP(D"+lastrow+";Foglio2!A1:C35;2;FALSE)");
var indirDest = cell3.getValue()
var cell4 = sheet.getRange("V"+lastrow);
cell4.setFormula("=VLOOKUP(D"+lastrow+";Foglio2!A1:C35;3;FALSE)");
var citDest = cell4.getValue()
//Ricava data
var day = sheet.getRange("W"+lastrow);
day.setFormula("=(DAY(A"+lastrow+"))");
var month = sheet.getRange("X"+lastrow);
month.setFormula("=(MONTH(A"+lastrow+"))");
var year = sheet.getRange("Y"+lastrow);
year.setFormula("=(YEAR(A"+lastrow+"))");
var day1 = sheet.getRange("W"+lastrow).getValue();
var month1 = sheet.getRange("X"+lastrow).getValue();
var year1 = sheet.getRange("Y"+lastrow).getValue();
var data = day1+"/"+month1+"/"+year1;
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' N° '+lastrow+' ' +mittente , folder)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyMittente', mittente);
copyBody.replaceText('keyDestinatario', destinatario);
copyBody.replaceText('keyQNT1', primaQnt);
copyBody.replaceText('keyDescrizione1', primaDescr);
copyBody.replaceText('keyQNT2', secondaQnt);
copyBody.replaceText('keyDescrizione2',secondaDescr);
copyBody.replaceText('keyQNT3', terzaQnt);
copyBody.replaceText('keyDescrizione3', terzaDescr);
copyBody.replaceText('keyQNT4', quartaQnt);
copyBody.replaceText('keyDescrizione4', quartaDescr);
copyBody.replaceText('keyQNT5', quintaQnt);
copyBody.replaceText('keyDescrizione5', quintaDescr);
copyBody.replaceText('keyAspetto', aspetto);
copyBody.replaceText('keyKg', peso);
copyBody.replaceText('keyColli', colli);
copyBody.replaceText('keyVettore', vettore);
copyBody.replaceText('keyIndirMitt', indirMitt);
copyBody.replaceText('keyCitMitt', citMitt);
copyBody.replaceText('keyIndirDest', indirDest);
copyBody.replaceText('keyCitDest', citDest);
copyBody.replaceText('keyNum', lastrow);
copyBody.replaceText('keyData', data);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "DDT";
var body = "In allegato il DDT generato tramite il portale SimplyCar.";
GmailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
// DriveApp.getFileById(copyId).setTrashed(true);
}

Google Script to watch multiple sheets: how do I simplify this script?

I am new to Google Scripts, and trying to automate some process in Google Spreadsheets. I have found a way to move a row from one sheet to another based on the value in a specific column. But, to make it work across multiple sheets, I have duplicated the code for every sheet. I'm sure there must be a way to simplify this, but I'm getting stuck. See my code below.
function onEdit() {
// moves a row from a sheet to another when a magic value is entered in a column
// adjust the following variables to fit your needs
// see https://productforums.google.com/d/topic/docs/ehoCZjFPBao/discussion
var sheetNameToWatch = "BRG";
var columnNumberToWatch = 3; // column A = 1, B = 2, etc.
var valueToWatch = "done";
var sheetNameToMoveTheRowTo = "Done";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}
var sheetNameToWatch = "Lesotho";
var columnNumberToWatch = 3; // column A = 1, B = 2, etc.
var valueToWatch = "done";
var sheetNameToMoveTheRowTo = "Done";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}
var sheetNameToWatch = "Bosman";
var columnNumberToWatch = 3; // column A = 1, B = 2, etc.
var valueToWatch = "done";
var sheetNameToMoveTheRowTo = "Done";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}
}
This should do it. It creates an array of all sheet names not equal to "Done" and then loops through your code to see if a sheet has been edited with "done" in column C.
function onEdit() {
var columnNumberToWatch = 3; // column A = 1, B = 2, etc.
var valueToWatch = "done";
var sheetNameToMoveTheRowTo = "Done";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
var sheetNameToWatch=[] //Array of Sheet names
var names = ss.getSheets()
for( j=0;j<names.length;j++) {
var n= names[j].getSheetName();
if(n!="Done"){ //If Sheet name not "Done" add to array
sheetNameToWatch.push(n)
}}
for(i=0;i<sheetNameToWatch.length;i++){
if (sheet.getName() == sheetNameToWatch[i] && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}}
}

Sending emails from a spreadsheet

I grabbed this script from: https://developers.google.com/apps-script/articles/sending_emails
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
I'm wondering if I would be able to make a dynamic subject line (per email). Is that possible?
Thank you!
James
Sure. Assuming that you put the value of the subject in the next column (D from you example), just do something like the following:
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
var subject = row[3];
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}