copy active row From one sheet to another google sheets - google-apps-script

I am having trouble copying a single row to a second sheet with google sheets.
I am using Google script editor to send automated email updates which works fine. However I am now trying to log each update from specific columns. I need all the information in the row to move with the cell that is edited.
Each Row is a separate job-site and I will have up to 30 concurrent job-sites going on at one time. So the update may come in in cell "M3" or "M28"
What I am trying to do is capture only the row that is edited not the whole sheet. My current code is copying the whole sheet. I am drawing a blank on how to just define the single row as active and set it to a range.
Here is what I have. I am no java script programmer but searching this site has gotten me this far. Bare with the code is not perfect.
function sendupdate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = '';
var message = '';
var techname = '';
var branchname = '';
var city = '';
var state = '';
var technumber = '';
if(cell.indexOf('M')!=-1){
message = sheet.getRange('B'+ sheet.getActiveCell().getRowIndex()).getValue()
techname = sheet.getRange('N'+ sheet.getActiveCell().getRowIndex()).getValue()
branchname = sheet.getRange('H'+ sheet.getActiveCell().getRowIndex()).getValue()
city = sheet.getRange('J'+ sheet.getActiveCell().getRowIndex()).getValue()
state = sheet.getRange('K'+ sheet.getActiveCell().getRowIndex()).getValue()
recipients = "(emailaddress";
var subject = ' Update: ' +techname + ' ' + message + ' ' + city + ' ' + branchname +' ' ;
var body = ': ' + message + ' Technician: « ' + techname + ' » New Update: « ' + cellvalue + ' » has been posted to the Update Sheet Visit ' + ss.getUrl() + ' to view the changes on row: ' + row + '';
MailApp.sendEmail(recipients, subject, body);
var target_sheet = ss.getSheetByName('Log')
var last_row = target_sheet.getLastRow();
target_sheet.insertRowAfter(last_row);
sheet.getRange('A:P').copyTo(target_sheet.getRange('A'+(last_row+1)+':P'+(last_row+1)));
}
debugger

Here is the code I added which made it work
var target_sheet = ss.getSheetByName('Log')
var last_row = target_sheet.getLastRow();
var activeRow = sheet.getRange( row ,1, 1 ,16)
target_sheet.insertRowAfter(last_row);
activeRow.copyTo(target_sheet.getRange('A'+(last_row+1)+':P'+(last_row+1)));

Get the Range of the active row by calling getRange(row, column, numRows). You can then use that range to copy it to the other sheets

Related

Sending email onEdit with the row data embedded into email in Google Sheets

I am creating a google script that when a person changes a column to "Approved" it sends an email out that grabs the cell that was changed. However, I am not a expert scripter at all and am having a hard time in figuring out how to get the script to call the information from the actual row into the email either.
Here is my script:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var cell = sheet.getActiveCell().getA1Notation();
var rowData = sheet.getActiveRange().getRow();getValue();
var row = sheet.getActiveRange().getRow();
var cellvalue = sheet.getActiveCell().getValue().toString();
var recipients = "test#sendemail.com";
var message = '';
if(cellvalue === 'Approved'){
message = 'Cell ' + cell + ' ' + ' ' + rowData + ' was changed to Approved.';
var subject = 'Cell Changed to Approved in Interns List';
var body = message;
MailApp.sendEmail(recipients, subject, body);
}
}
I couldnt find any solution thats been done already that would include the entire row that was triggered.
Try this:
function onMyEdit(e) {
const sh=e.range.getSheet();
var rowData = sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0].join(',');
var recipients = "test#sendemail.com";
var message = '';
if(e.value == 'Approved'){
message = 'Cell ' + e.range.getA1Notation() + ' ' + ' ' + rowData + ' was changed to Approved.';
var subject = 'Cell Changed to Approved in Interns List';
MailApp.sendEmail(recipients, subject, message);
}
}

Auto Send Email When Checkbox is Checked - Google Sheet

I tried the script from Auto Email Function for Google Sheets Mobile and it worked the first time. When I tried to change the variables, it does not automatically send the email, unless I run the script again, it would then update the response sheet and then clears the checkbox. Please help me with this. Kindly see my code below.
function EmailNotification(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Course_AutoEmail'); //source sheet
var columnb = sheet.getRange('I:I'); //Column with check boxes
var columnbvalue = columnb.getValues();
var notifysheet = ss.getSheetByName('Responses'); //destination sheet
var data = [];
var rownum = [];
//Condition check in B:B (or check box column); If true copy the same row to data array
for (let i = 0; i < columnbvalue.length; i++) {
if (columnbvalue[i][0] === true) {
var columnb2 = sheet.getRange('I747:I'); //row started in row 747
columnb2.setValue('false');
data.push.apply(data, sheet.getRange(i + 1, 1, 1, 20).getValues());
//Copy matched ROW numbers to rownum
rownum.push(i);
//Copy data array to destination sheet
notifysheet.getRange(notifysheet.getLastRow() + 1, 1, data.length, data[0].length).setValues(data);
var activeRow = notifysheet.getLastRow();
var name = notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var employeeID = notifysheet.getRange(activeRow, 2).getDisplayValue();
var position = notifysheet.getRange(activeRow, 3).getDisplayValue();
var team = notifysheet.getRange(activeRow, 4).getDisplayValue();
var date = notifysheet.getRange(activeRow, 10).getDisplayValue();
var rec1 = notifysheet.getRange(activeRow, 19).getDisplayValue();
var rec2 = notifysheet.getRange(activeRow, 20).getDisplayValue();
var email = rec1 + "," + rec2;
var subject = name + ': 201 Completion';
//Body of the email message, using HTML and the variables from above
var message =
'<br><div style="margin-left:10px;">Hi, </div>' +
'<br><div style="margin-left:10px;">Good day!</div>' +
'<br><div style="margin-left:10px;"><b>' + name + '</b> has completed the course. </div>' +
'<br><div style="margin-left:20px;"><h3 style="text-decoration: underline; color: #f36f21">Employee Details: </h3></div>' +
'<div style="margin-left:25px;">Name: <b>' +
name +
'</b></div>' +
'<div style="margin-left:25px;">Position: <b>' +
position +
'</b></div>' +
'<div style="margin-left:25px;">Team: <b>' +
team +
'</b></div>' +
'<div style="margin-left:25px;">Completion Date: <b>' +
date +
'</b></div>' +
'<br><br><div style="margin-left:10px;">Let me know if you have any questions. </div>' +
'<br><div style="margin-left:10px;">Thanks! </div>';
MailApp.sendEmail(email, subject, '', {
htmlBody: message,
name: 'Updates',
});
}
}
}
I read your code.
if you don't want your checked checkbox unchecked in spreadsheet.
so you have to remove `columnb2.setValue('false');` line of code.
this line is made checkbox unchecked.
solution of other problems : http://one7techlab.com

Comparing Dates in Google Sheets Script Editor

I am very new to this, so please bear with me. I am trying to get my code to look at each cell in a column, then compare that date to the current date, and if they match send an email. I am aware I will need a loop of some sort to get it to look through the column, but I haven't even gotten that far. I've tried every method I can find online to just get it to compare one cell to the date and send the email.
I tested the email function prior to adjusting it to compare the date, so I know that is working. Put something definitely isn't working...
function sendEmail() {
//Fetch the date
var removalDateRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("E2");
var removalDate = removalDateRange.getValue();
var currentDateRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var currentDate = new Date();
var ui = SpreadsheetApp.getUi();
//Check Date
if (removalDate == currentDate) {
//Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var emailAddress = emailRange.getValue();
//Fetch Item Brand
var itemBrandRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("B2");
var itemBrand = itemBrandRange.getValue();
//Fetch Item Name
var itemNameRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("A2");
var itemName = itemNameRange.getValue();
//Fetch Item Location
var itemLocationRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("H2");
var itemLocation = itemLocationRange.getValue();
// Send Alert Email
var message = 'The ' + itemBrand + ' ' + itemName + ' in ' + itemLocation + ' will expire in 2 months. Please use and replace item.';
// Second Column
var subject = 'Pantry Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
EDIT
Okay, I had it working late last night and even got it to loop through, and somehow I've broken it again. I've been looking at answers for hours trying to adjust things to make it work. What am I doing wrong?
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
// 2 months from now
var oneMonthFromToday = new Date(todayYear, todayMonth, todayDay);
var oneMonthMonth = oneMonthFromToday.getMonth() + 2;
var oneMonthDay = oneMonthFromToday.getDate();
var oneMonthYear = oneMonthFromToday.getYear();
// getting data from spreadsheet
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Exp");
var startRow = 2; // First row of data to process
var numRows = 500; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 999);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(new Date(row[5]),
'ET',
'MM/dd/yyyy'
);
//email Information
var subject = 'Pantry Item Needs Attention!';
var message1 =
row[6] + ' ' + row[3] + ' of ' + row[2] + ' ' + row[1] + ' will expire on ' + expireDateFormat + '. Item can be found in ' + row[7]
+ '. Please Remove and Replace Item.' +
'\n' + 'Thanks Steve!';
var message2 =
row[6] + ' ' + row[3] + ' of ' + row[2] + ' ' + row[1] + ' will expire on ' + expireDateFormat + '. Item can be found in ' + row[7] +
'. Please ensure item has been replaced, removed from the pantry, and deleted from inventory.' +
'\n' + 'Thanks Steve!'
//expiration date information
var expireDateMonth = new Date(row[5]).getMonth() + 1;
var expireDateDay = new Date(row[5]).getDate();
var expireDateYear = new Date(row[5]).getYear();
//checking for today
if (
expireDateMonth === todayMonth &&
expireDateDay === todayDay &&
expireDateYear === todayYear
) {
ui.alert(message1);
}
}
}
Dates can be frustrating to work with, so consider doing the whole thing (loop, if then statement...) with an integer first and then returning to the date part if you're having trouble. That said, try adjusting the top of your code to look like the following:
var ss =SpreadsheetApp.getActiveSpreadsheet();
var removalDateVal = ss.getSheetByName("Expirations").getRange("E2").getValue();
var removalDate = new Date(removalDateVal);
var currentDateVal = ss.getSheetByName("Alerts").getRange("C2").getValue();
var currentDate = new Date(currentDateVal);
That will give you two date objects. But BEWARE! These dates contain time as well as calendar date so they may not equal each other even when they appear to. Use setHours() to zero out the date as seen below.
currentDate.setHours(0,0,0);
removalDate.setHours(0,0,0);
Other notes, it's best practice to set a variable for a spreadsheet and worksheet as shown by Google here. It makes the code much more readable.

Can you Sendnotification in Google Script for multiple sheets?

I'd like to send a notification to someone when a particular cell (ie document) is updated. Specifically, when a cell in one row is updated, it would send a notification to the owner listed in the same row. For example B47 gets updated, it send an email to B3.
I've gotten the script to work when it's pointed to one sheet. But when I try to ask the script to run over multiple sheets/tabs, I get error 'Script function not found: sendNotification' Is it possible to have this script work for multiple sheets/tabs in the same google doc? Updates are pulling from a different source so I'd like to keep using getSheetbyName instead of getActiveSheet.
Any help would be much appreciated. Here's my code where it stands:
function shellFunction() {
var sheets = ['Arabic', 'Portuguese'];
for (var s in sheets) {
toTrigger(sheets[s]);
}
function toTrigger(sheetName) {
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheets[s]);
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = sheet.getRange('J' + sheet.getActiveCell().getRowIndex()).getValue();
var message = '';
if (cell.indexOf('B') != -1) {
message = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'The ' + sheet.getRange('F' + sheet.getActiveCell().getRowIndex()).getValue() + ' ' + sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' needs your Translation';
var body = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' has been updated. Can you please update ' + sheet.getRange('G' + sheet.getActiveCell().getRowIndex()).getValue() + '? Please remember to update the date column in the Resource Document when the translation is complete:' + ss.getUrl();
MailApp.sendEmail(recipients, subject, body);
}
}
}
Should this line
var sheet = ss.getSheetByName(sheets[s]);
be changed to
var sheet = ss.getSheetByName(sheetName);
since that is the name of the passed sheet?
EDIT
There were a couple other items which may have caused issue. I made edits for this result:
function shellFunction() {
var sheets = ['Arabic', 'Portuguese'];
for (var s in sheets) {
toTrigger(sheets[s]);
}
}
function toTrigger(sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = sheet.getRange('J' + sheet.getActiveCell().getRowIndex()).getValue();
var message = '';
if (cell.indexOf('B') != -1) {
message = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'The ' + sheet.getRange('F' + sheet.getActiveCell().getRowIndex()).getValue() + ' ' + sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' needs your Translation';
var body = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' has been updated. Can you please update ' + sheet.getRange('G' + sheet.getActiveCell().getRowIndex()).getValue() + '? Please remember to update the date column in the Resource Document when the translation is complete:' + ss.getUrl();
MailApp.sendEmail(recipients, subject, body);
}
My first change was to not nest the functions. To do this I added a closing curly bracket before the toTrigger function and removed one of the last in your code. After that there was another nested function which actually made up all of the toTrigger function. It was called sendNotifocation which matched your error. I removed that by removing the line after the toTrigger function declaration and another curly bracket at the end of your code.
Last, I made the above edit. In my test it seemed to work fine, except that I commented out the call to actually send an email and only debugged to the line just prior to that point.

Google Apps Script Email Notification Not Functioning Correctly

I could really use some help, and I'd really appreciate any pointers anyone can give. I know there are some other similar questions out there, but from what I can find, no one else has this specific issue/request.
I have a Google Sheet that three different people collaborate on. I have this notification script that will notify specific users via email about any changes to any of the cells in the F column. Importantly, this email notification also contains the value of the A cell in that row that has had it's F cell value changed.
However, what I'm really trying to achieve is a notification script that will email a specified person only when any cell in column F has a new value of "Yes" in Sheet2 of the master sheet.
The code I have so far is (that sends a notification when any change happens in the F column):
function sendNotification(e) {
var received = e.value; //Gets the value of the edited cell
};
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet 2");
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var received = ss.getRange('F2:F').getValue();
var recipients = "example#gmail.com";
var message = '';
if(received==="Yes"){
message = sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue()
var subject = 'A cell value '+ sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue() + ' has been received';
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '». For message: «' + message + '»';
MailApp.sendEmail(recipients, subject, body)};
Logger.log('received value: ' + received);
};
If it helps, below is a code that works in my tests : (set up an installable trigger to make it work)
note : I added a couple of Logger.log here and there to check the variables and a Browser message to avoid sending mails while testing.
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet 2");
var cell = ss.getActiveCell();
var row = sheet.getActiveRange().getRow();
var col = cell.getA1Notation().replace(/[0-9]/g,'').toLowerCase();
Logger.log('col = '+col);
var cellValue = cell.getValue().toString().toLowerCase();
Logger.log(cellValue);
var recipients = "example#gmail.com";
var message = '';
Logger.log(cellValue=="yes" && col=='f');
if(cellValue=="yes" && col=='f' ){
message = sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue()
var subject = 'A cell value '+ sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue() + ' has been received';
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellValue + '». For message: «' + message + '»';
// MailApp.sendEmail(recipients, subject, body)
Browser.msgBox('mail sent');
}
Logger.log('message body: ' + body);
};
To set up an event object use:
function sendNotification(e) {
var received = e.value; //Gets the value of the edited cell
};
The code that is sending the email, is outside of the if body. So the email is being sent no matter what.
Change to this:
if(received==="Yes"){
message = sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue()
var subject = 'A cell value '+ sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue() + ' has been received';
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '». For message: «' + message + '»';
MailApp.sendEmail(recipients, subject, body);
};
In this line of code:
if(received="Yes"){
You are using an assignment operator to check for equality. Equality checks are done with double or triple equal signs.
Should be:
if(received==="Yes"){