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

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());
}}
}

Related

Same variable for multiple sheets but only execute if export button on one sheet is pressed

I am trying to code an data export. The export is executed when a button is pressed and the script linked to the button will be executed. The data is transfered to a masterdata sheet.
The script is valid for 4 different sheets and i am trying to code it, so that i do not have to rename all the vaiables for each sheet.
I found some solution that i tried, by creating a variable with the sheet names and then call this variable in the following code.
Problem 1: Error "TypeError: Cannot read property 'copyTo' of null" occurs.
Problem 2: How to ensure that only the data from the sheet where the export button is pressed will be exported?
I tried a lot and cannot find a solution.
var sheetListArray = ["B1-Prozessfragen", "B2-Prozessfragen"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
for( var k = 1 ; k <= sheetListArray.length ; k++)
ExportData1g (sheetListArray[k]);
PB1g (sheetListArray[k]);
function ExportData1g (sheetname) {
var result = SpreadsheetApp.getUi().alert("Fertig-Hacken gesetzt?", SpreadsheetApp.getUi().ButtonSet.OK_CANCEL); {
if (result === SpreadsheetApp.getUi().Button.OK) {
const ssh=ss.getSheetByName(sheetname);
const cell = ssh.getRange("CheckButton1").getValue();
if (cell == "1" || "0") {
(PB1g ());
}
else {return;} }
else {return;}
}
const ssh=ss.getSheetByName(sheetname);
var dataRange = ssh.getRange('CheckBox1');
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == true) {
values[i][j] = false;
}}
dataRange.setValues(values);
var commentRange = ssh.getRange ('ResetComment1');
var dataRange = ssh.getRange('EmptyBoxes1');
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == 1) {
values[i][j] = 0;
}
}
}
commentRange.clearContent();
dataRange.setValues(values);
} }
function PB1g(sheetname) {
const ssh=ss.getSheetByName(sheetname);
const tss=SpreadsheetApp.openById("1wMw5H48Fmc1R8WGy34d80x9-W996c9GNVuAD3-mFtVQ");
const tsh=tss.getSheetByName("PB");
const nsh=ssh.copyTo(tss);
var firstEmtyRow = tsh.getLastRow () + 1;
var timestamp = new Date();
tsh.appendRow([timestamp]);
nsh.getRange("CopytoMasterdata1").copyTo(tsh.getRange("B" + firstEmtyRow), {contentsOnly:true});
tss.deleteSheet(nsh); }

EPPlus two color conditional date format

I have a column with dates and I want to conditionally color any cell that is older that 2 week yellow, and any that is older than 90 days red. I can't figure out how to do that.
Should be able to just add the conditions like any other. You can use the TODAY() function in excel and subtract:
[TestMethod]
public void Conditional_Formatting_Date()
{
//https://stackoverflow.com/questions/56741642/epplus-two-color-conditional-date-format
var file = new FileInfo(#"c:\temp\Conditional_Formatting_Date.xlsx");
if (file.Exists)
file.Delete();
//Throw in some data
var dataTable = new DataTable("tblData");
dataTable.Columns.AddRange(new[] {
new DataColumn("Col1", typeof(DateTime)),
new DataColumn("Col3", typeof(string))
});
var rnd = new Random();
for (var i = 0; i < 100; i++)
{
var row = dataTable.NewRow();
row[0] = DateTime.Now.AddDays(-rnd.Next(1, 100));
row[1] = $"=TODAY() - A{i +1}";
dataTable.Rows.Add(row);
}
//Create a test file
using (var package = new ExcelPackage(file))
{
//Make the stylesheet
var ws = package.Workbook.Worksheets.Add("table");
var range = ws.Cells[1, 1].LoadFromDataTable(dataTable, false);
ws.Column(1).Style.Numberformat.Format = "mm-dd-yy";
ws.Column(1).AutoFit();
//Add the calc check
var count = 0;
foreach (DataRow row in dataTable.Rows)
ws.Cells[++count, 2].Formula = row[1].ToString();
//Add the conditions - order matters
var rangeA = range.Offset(0, 0, count, 1);
var condition90 = ws.ConditionalFormatting.AddExpression(rangeA);
condition90.Style.Font.Color.Color = Color.White;
condition90.Style.Fill.PatternType = ExcelFillStyle.Solid;
condition90.Style.Fill.BackgroundColor.Color = Color.Red;
condition90.Formula = "TODAY() - A1> 90";
condition90.StopIfTrue = true;
var condition14 = ws.ConditionalFormatting.AddExpression(rangeA);
condition14.Style.Font.Color.Color = Color.Black;
condition14.Style.Fill.PatternType = ExcelFillStyle.Solid;
condition14.Style.Fill.BackgroundColor.Color = Color.Yellow;
condition14.Formula = "TODAY() - A1> 14";
package.Save();
}
}
Which gives this in the output:
I am assuming that you have the column number of the date column and number of rows in your records. Also, the following loop is under assumption that the first row is your column header and records begin from second row. Change the loop counter's initialization and assignment accordingly.
int rowsCount; //get your no of rows
int dateColNumber; //Assign column number in excel file of your date column
string cellValue;
DateTime dateValue;
DateTime today = DateTime.Now;
double daysCount;
for(int i=1;i<rowsCount;i++)
{
cellValue = ws.Cells[i + 1, dateColNumber].Text.ToString(); //First row is header start from second
if(DateTime.TryParse(cellValue,out dateValue))
{
daysCount = (today - dateValue).Days;
if(daysCount>90)
{
ws.Cells[i + 1,dateColNumber].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
ws.Cells[i + 1,dateColNumber].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
}
else if(daysCount>14)
{
ws.Cells[i + 1, dateColNumber].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
ws.Cells[i + 1, dateColNumber].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
}
}
}

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

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)
...

Trying to create multiple PDF for each row in a Google Sheet

I am trying to create a separate PDF for each row in a Google Sheet using a Google Doc as a template. I can get it to work when I use the active row; however, when I try to loop the createpdf function the only PDF I am left with is the last row. My thoughts are that I am deleting all of the files beforehand but I can't figure out where the error is. Any help would be awesome.
var TEMPLATE_ID = '1Mxrm0kny8R7ROlBou8kSUc8dOvvH8PvtQ-EC_Nd3FUQ';
function onOpen() {
SpreadsheetApp
.getUi()
.createMenu('Create PDF')
.addItem('Create PDF', 'createPdf')
.addToUi();
}
for (var i=2; i < 3; i++) { function createPdf() {
if (TEMPLATE_ID === '') {
SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs');
return;
}
// Set up the docs and the spreadsheet access
var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
copyId = copyFile.getId(),
copyDoc = DocumentApp.openById(copyId),
copyBody = copyDoc.getBody(),
activeSheet = SpreadsheetApp.getActiveSheet(),
numberOfColumns = activeSheet.getLastColumn(),
activeRow = activeSheet.getRange(i, 1, 1, numberOfColumns).getValues(),
headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
columnIndex = 0,
fileName = activeRow[0][0] + activeRow[0][1],
pdfFile,
pdfFile2;
// Replace the keys with the spreadsheet values
for (;columnIndex < headerRow[0].length; columnIndex++) {
copyBody.replaceText('%' + headerRow[0][columnIndex] + '%',
activeRow[0][columnIndex]);
}
// Create the PDF file and delete the doc copy
copyDoc.saveAndClose();
pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf"));
pdfFile2 = pdfFile.setName(fileName)
copyFile.setTrashed(true);
return pdfFile2;
}}
Tip: pay attention to formatting your code properly, because it will help you understand its structure. Here's what you have after passing it through jsbeautifier:
var TEMPLATE_ID = '1Mxrm0kny8R7ROlBou8kSUc8dOvvH8PvtQ-EC_Nd3FUQ';
function onOpen() {
SpreadsheetApp
.getUi()
.createMenu('Create PDF')
.addItem('Create PDF', 'createPdf')
.addToUi();
}
for (var i = 2; i < 3; i++) {
function createPdf() {
if (TEMPLATE_ID === '') {
SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs');
return;
}
// Set up the docs and the spreadsheet access
var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
copyId = copyFile.getId(),
copyDoc = DocumentApp.openById(copyId),
copyBody = copyDoc.getBody(),
activeSheet = SpreadsheetApp.getActiveSheet(),
numberOfColumns = activeSheet.getLastColumn(),
activeRow = activeSheet.getRange(i, 1, 1, numberOfColumns).getValues(),
headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
columnIndex = 0,
fileName = activeRow[0][0] + activeRow[0][1],
pdfFile,
pdfFile2;
// Replace the keys with the spreadsheet values
for (; columnIndex < headerRow[0].length; columnIndex++) {
copyBody.replaceText('%' + headerRow[0][columnIndex] + '%',
activeRow[0][columnIndex]);
}
// Create the PDF file and delete the doc copy
copyDoc.saveAndClose();
pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf"));
pdfFile2 = pdfFile.setName(fileName)
copyFile.setTrashed(true);
return pdfFile2;
}
}
The indenting clarifies a few problems:
The for loop on i is in global scope, not part of any function. It will therefore execute every time ANY function in the script is invoked, but is not explicitly invocable, as it would be in a function.
The function createPDF is declared inside that for loop. This is in global scope (see point 1), so it's still available to be called from other functions such as the menu created by your onOpen(). HOWEVER, because it's just a declaration, it is NOT invoked by the i loop! (This was the primary concern of your question.)
There's a return call inside createPdf() that is probably a left-over from the original copy of this code which produced a single PDF. Because it returns in the first time through the loop, it will STILL make a single PDF. That line needs to be moved or deleted.
return pdfFile2;
Flipping those couple of lines and deleting the return should sort us out.
var TEMPLATE_ID = '1Mxrm0kny8R7ROlBou8kSUc8dOvvH8PvtQ-EC_Nd3FUQ';
function onOpen() {
SpreadsheetApp
.getUi()
.createMenu('Create PDF')
.addItem('Create PDF', 'createPdf')
.addToUi();
}
function createPdf() {
for (var i = 2; i < 3; i++) {
if (TEMPLATE_ID === '') {
SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs');
return;
}
// Set up the docs and the spreadsheet access
var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
copyId = copyFile.getId(),
copyDoc = DocumentApp.openById(copyId),
copyBody = copyDoc.getBody(),
activeSheet = SpreadsheetApp.getActiveSheet(),
numberOfColumns = activeSheet.getLastColumn(),
activeRow = activeSheet.getRange(i, 1, 1, numberOfColumns).getValues(),
headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
columnIndex = 0,
fileName = activeRow[0][0] + activeRow[0][1],
pdfFile,
pdfFile2;
// Replace the keys with the spreadsheet values
for (; columnIndex < headerRow[0].length; columnIndex++) {
copyBody.replaceText('%' + headerRow[0][columnIndex] + '%',
activeRow[0][columnIndex]);
}
// Create the PDF file and delete the doc copy
copyDoc.saveAndClose();
pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf"));
pdfFile2 = pdfFile.setName(fileName)
copyFile.setTrashed(true);
}
}

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();
}
}
}