I looking for script, that will create audit log in another sheet. In this log it should be:
1)Time stamp
2)User who edited cell
3)The value of the edited cell
I tryed many of tutorial, but I am really new in this and little lost.
This script will log all activities in the sheet "Logging"
function onEdit(e) {
var email = Session.getEffectiveUser().getEmail();
var timeZone = Session.getScriptTimeZone();
var key = Session.getTemporaryActiveUserKey();
var sName = e.source.getActiveSheet().getSheetName();
if(sName !== "Logging") {
var value;
var mA1 = e.range.getA1Notation().split(":")[0];
if(typeof(e.value) == 'string') {
var aCell = e.source.getRange(mA1);
value = aCell.getValue();
var form = "'" + aCell.getFormula();
} else {
value = e.value;
}
var data = [sName, mA1, timeZone, email, key, value, form];
e.source.getSheetByName("Logging").appendRow(data);
}
}
Related
Can i get this script to work from sheet id or sheet name
This script works when i use the active spreadsheet but i want it to get it from the spreadsheet name or the sheet id. If i add .getSheetByName("Test") to line 2 it returns "TypeError: Cannot read property 'getRange' of null"
i am running the script from the sheet named "test" and there is a value in cell a1
Thanks in advance for the help
function CheckPrice() {
var priceRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A1").getValue();
var ui = SpreadsheetApp.getUi();
if (priceRange < 10){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A2");
var emailAddress = emailRange.getValue();
var message = 'This is your Alert email!';
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
} ```
Change twice SpreadsheetApp.getActiveSpreadsheet() to SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mySheetName')
For instance
function CheckPrice() {
var priceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A1").getValue();
// get value from cell a1
var ui = SpreadsheetApp.getUi();
if (priceRange < 10){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A2");
// get email from cell a2
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your Alert email!';
var subject = priceRange + " %up";
// adds cell value to subject
MailApp.sendEmail(emailAddress, subject, message); }
}
I'm trying to write a script where an automatic email is sent to a specific person upon edit of a cell and the cell equals "Done". However, I want the subject to be the first cell of the edited row. Cell that will contain "Done" is always going to be in the AA Column, and I want the subject to be the A column of the same row. Ex: AA3 was edited so subject is A3. I have spent hours sifting through tutorials and came up with this:
function checkValue() {
var sp = PropertiesService.getScriptProperties();
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Accts");
var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
if (valueToCheck = 'Done') {
MailApp.sendEmail("a***a#gmail.com", activeCell.offset(-26,0).getValue(), Email.html);
}
}
Am I doing this entirely wrong or is there hope?
EDIT:
Now that it's resolved. I thought I'd share what my script ended up looking like. I added a UI and an option to execute using a menu option. Hope this helps someone else.
function onEdit(e)
{
var editRange = { // AA2:AA1000
top : 2,
bottom : 1000,
left : 27,
right : 27
};
// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;
var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;
var thisthang = e.value;
var doit = 'TRUE'
// We're in range; timestamp the edit
if(thisthang == doit)
{
doFinish();
}
else{return};
}
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Finished')
.addItem('Finish', 'doFinish')
.addToUi();
}
function doFinish()
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var row = cell.getRow();
var Campaign = getCampaignFromRow(row, 1);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Finish '+Campaign.name+'?', ui.ButtonSet.YES_NO);
if(response == ui.Button.YES)
{
handleFinish(row, Campaign);
}
if(response == ui.Button.NO)
{
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('FALSE');
}
}
function getCampaignFromRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row, 1).getValues();
var rec = values[0];
var Campaign =
{
Campaign_Name: rec[0]
};
Campaign.name = Campaign.Campaign_Name;
return Campaign;
}
function handleFinish(row, Campaign)
{
var templ = HtmlService
.createTemplateFromFile('Campaign-email');
templ.Campaign = Campaign;
var message = templ.evaluate().getContent();
MailApp.sendEmail({
to: "a***a#gmail.com",
subject: "A Campaign has been finished!",
htmlBody: message
});
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('TRUE');
}
You are trying to trigger an email when the spreadsheet is edited on the "Accts" sheet, in Column "AA" and the value = "Done".
The best solution is to use an onEdit trigger and also make use of Event Objects. In the case, "a simple trigger cannot send an email" ref, so you will need to create an Installable Trigger.
The main differences to your script are:
- var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
- a couple of things here.
- 1) you are trying to get all the values in the column, but you use the getValue (the method for a single cell) instead of getValues.
- 2) you could have defined the ActiveCell and just returned that value
- 3) though you tried to get the values for the entire column, your if statement is designed as though there is a single value rather than an array of values.
- 4) This demonstrates the benefit of the using the Event Objects. You can succinctly get the values of the edited cell and sheet.
- in your if comparison, you use "="; this is only used to assign a value. When comparing values you must use "==" or "===".
- To get the value of the "subject", the script uses the row number derived from the Event Objects; compared to the offset in your script - they are both acceptable. I used the getRange to demonstrate the alternative.
- your email body was defined as "Email.html", but this isn't declared. The answer uses a very simple body but could just as easily use another solution.
function so5967209001(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
// establish the values to be checked
var checkSheetname = "Accts"
var checkValue = "Done"
var checkColumn = 27; // column AA
// this will return the event objects
//Logger.log(JSON.stringify(e)); // DEBUG
// variables to use for checking
var editedrange = e.range;
var editedrow = editedrange.getRow();
var editedcolumn = editedrange.getColumn();
var editedsheet = editedrange.getSheet().getSheetName();
var editedvalue = e.value;
//Logger.log("DEBUG: row = "+editedrow+", column = "+editedcolumn+", sheet = "+editedsheet+", value"+editedvalue)
// test the sheet, the column and the value
if (editedsheet ==checkSheetname && editedcolumn==checkColumn && editedvalue == checkValue){
//Logger.log("DEBUG: this is a match");
var subject = sheet.getRange(editedrow,1).getValue(); // Column A of the edited row
//Logger.log("DEBUG: email subject = "+subject);
// build your own body
var body = "this is the body of the email"
// send the email
MailApp.sendEmail("ejb#tedbell.com.au", subject, body);
//Logger.log("DEBUG: mail sent")
}else{
//Logger.log("DEBUG: this isn't a match");
}
}
I have a script that is based on hardcoding the Name of a sheet in Google Sheets. It works but this means that the script needs to be updated if the name of the Sheet changes. Using the Id will mean that the sheet does not have to be protected, I would like the user to be able to re-name the sheet.
Can the below script be changed to use the ID of a sheet, instead of the Name?
This script assumes a gid=0 and updates an audit timestamp in the columns to the right of Column F for a row that has changed.
function onEdit(event) {
var name = event.range.getSheet().getName();
switch (name) {
case "AA":
update(event)
break;
}
}
function update(event) {
var ColF = 6; // Column Number of "F"
var changedRange = SpreadsheetApp.getActiveRange();
if (changedRange.getColumn() == ColF) {
if (changedRange.getRowIndex() >=7 ) {
// An edit has occurred in Column F
var state = changedRange.getValue();
var adjacentDate = SpreadsheetApp.getActive().getSheetByName("AA").getRange(changedRange.getRow(),ColF+4);
var adjacentDate2 = SpreadsheetApp.getActive().getSheetByName("AA").getRange(changedRange.getRow(),ColF+2);
var adjacentLDAP = SpreadsheetApp.getActive().getSheetByName("AA").getRange(changedRange.getRow(),ColF+3);
var adjacentLDAP2 = SpreadsheetApp.getActive().getSheetByName("AA").getRange(changedRange.getRow(),ColF+1);
var timestamp = new Date(); // Get the current time
adjacentDate2.setValue(timestamp);
adjacentLDAP2.setValue(Session.getEffectiveUser().getEmail());
if (adjacentDate.getValue() == "") {
// Write timestamp into adjacent cell
adjacentDate.setValue(timestamp);
adjacentLDAP.setValue(Session.getEffectiveUser().getEmail());
}
}
}
}
I'm working in Google Sheets on what is going to be a regularly accessed and edited document. What I would like is to have a column labelled "Date of Last Edit" and for each cell in that column to reflect the date of each cell row most recent edit. For example, if I edit info in cell C3 then I want the cell in column "Date of Last Edit" Row 3 to reflect the date I made the edit. I've found a few that are run by column but they only work for an individual column. I need it to cover all cells in a row that fall in front of "Date of Last Edit."
add this script to your sheet and change format and time zone if you need so ("GMT+1", "dd.MM.yyyy"):
function onEdit(event)
{
var sheet = event.source.getActiveSheet();
// note: actRng = the cell being updated
var actRng = event.source.getActiveRange();
var index = actRng.getRowIndex();
var cindex = actRng.getColumnIndex();
var dateCol = sheet.getLastColumn();
var lastCell = sheet.getRange(index,dateCol);
var date = Utilities.formatDate(new Date(), "GMT+1", "dd.MM.yyyy");
lastCell.setValue(date);
}
This code will update C:C with the email address of the user, and D:D with the current time of the same row if A:B are edited on the Data Entry tab. You'll need to set up an onChange() trigger to get it to work.
function userUpdate() {
/*
Changed the updated by/on to make it faster
Put in handling to make sure that if they delete a cell, that it only clears out the submitted by/on if ALL the values in A:B are blank
*/
// Main sheet details
var s = SpreadsheetApp.getActiveSheet();
var spreadsheetTimeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var lastUpdatedString = Utilities.formatDate(new Date(), spreadsheetTimeZone, "MM/dd/yyyy' 'HH:mm:ss");
var sessionEmail = Session.getActiveUser().getEmail();
// Check Sheet
if (s.getName() == "Data Entry") { //checks that we're on the correct sheet
var r = s.getActiveCell();
var row = r.getRowIndex();
var column = r.getColumn();
var activeRange = s.getRange("A" + row + ":B" + row);
//var activeRangeValues =
var activeRangeValuesLength = activeRange.getValues().toString().length;
if (row > 1) {
// Declare variables
var cellValue = r.getValue().toString();
// If the cellValue IS blank
if (activeRangeValuesLength < 5) {
sessionEmail = "";
lastUpdatedString = "";
}
// Update Submitted By / Submitted On
if (column < 5) {
var lastUpdatedBy = s.getRange("C" + row)
lastUpdatedBy.setValue(sessionEmail); // update column C
var lastUpdated = s.getRange("D" + row)
lastUpdated.setValue(lastUpdatedString); // update column D
}
}
}
I'm trying to create an app script that you can type in the name and username of an individual and select various dates associated with their training. I'm nearly done with the project but one piece of script is giving me issues. What the script is supposed to do is take the User Name I've entered into the app and see if that value already exists in column L of the archive. If the value exists then it should return an alert with a YES_NO option and depending on what is selected it will either cancel the import or continue on and import the username to the sheet.
I've been trying to figure out this script for about 5 days and cannot figure it out. I've tried pretty much everything I can think of. Here's the code. The Username already exists in Cell L3 of the Archive.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getRange("L3").getValues();
if(tD == usern )
{
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert('Wait', 'The Username you are trying to use has already been archived. Would you still like to continue?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.Yes) {
// User clicked "Yes".
SpreadsheetApp.getActiveSpreadsheet().toast('Error Report Has Been Updated', 'UPDATE ERRORS',3);
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(), 'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}else {
// User clicked "No" or X in the title bar.
ui.alert('Import Canceled');
}
}else{
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(),
'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}
}
This script Works as long as I am referencing One Cell so tM.getRange("L3").getValues(); Works. However, As soon as I change that to tM.getRange("L3:L").getValues(); it does not recognize the value exists within the range and returns the else portion of the code.
I have also tried a loop for the top section that is giving me issues but the same thing is happening. As soon as I try to find a value within the column rather than a specific cell it won't work. Here is what it looks like with the loop.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getDataRange().getValues();
for(var i = 0; i<tD.length; i++){
if(tD[i][11] == usern )
{
If anyone can figure out what i'm doing wrong or why it's not working as soon as I reference the entire column any help would be greatly appreciated.
Thanks!