AppScript Select active range - google-apps-script

so i am trying to when i select any column form the row, returns me the column E value, some one know how?
i don't know if i made me clear, but the idea is save the value and display after in a sidebar as default value
i have onde function who does something similar, but i don't know how works
function notifyReporterForm() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_BUGS);
var row = ss.getLastRow(), column = 1, numRows = 1, numColumns = ss.getLastColumn();
var values = ss.getRange(row, column, numRows, numColumns).getValues();
var to = values[0][2];
var user_email = values[0][3];
var ticketNo = values[0][0];
var openedDate = values[0][1]
var details = ''
var summary = values[0][6]
var text = values[0][6].split('\n')
var image_url = values[0][8]
text.map(row => {
if(row){
details += '<p>' + row + '</p>'
}
})

function onSelectionChange(e) {
const sh = e.range.getSheet();
e.source.toast(sh.getRange(e.range.rowStart,5).getValue());
e.range.setValue(sh.getRange(e.range.rowStart,5).getValue());
}

Related

LastRow in certain column in google sheet

Any idea how to get lastRow at certain column, in this case i want the lastRow for range AJ until AX only.
var emailUser = Session.getActiveUser().getEmail();
var ss2 = SpreadsheetApp.openById('1h2jmWV7mytPF_ltxYb2uPm4Pq7iHLg-hc3k_0X4Txvw');
var ws2 = ss2.getSheetByName(emailUser);
var lastRow = ws2.getLastRow();
var rdPic = ws2.getRange(3,36,lastRow,50).getValues();
var lrPic = rdPic.filter(String).length + 1;
ws2.getRange("AJ"+lrPic).setValue(stock.tglMasuk1);
ws2.getRange("AK"+lrPic).setValue(stock.namaPic1);
ws2.getRange("AL"+lrPic).setValue(stock.locPIC1);
ws2.getRange("AM"+lrPic).setValue(stock.teritori1);
ws2.getRange("AN"+lrPic).setValue(stock.penyimpanan1);
ws2.getRange("AO"+lrPic).setValue(stock.jenisTransaksi1);
ws2.getRange("AP"+lrPic).setValue(stock.nmrDO1);
ws2.getRange("AQ"+lrPic).setValue(stock.tglDO1);
ws2.getRange("AR"+lrPic).setValue(stock.sn1);
ws2.getRange("AS"+lrPic).setValue(stock.venname1);
ws2.getRange("AT"+lrPic).setValue(stock.itm1);
ws2.getRange("AU"+lrPic).setValue(stock.ponum1);
ws2.getRange("AV"+lrPic).setValue(stock.bcd1);
ws2.getRange("AW"+lrPic).setValue(emailUser);
ws2.getRange("AX"+lrPic).setValue(dateNow);

Google Script timing out when grabbing rows from Database (MYSQL)

function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
while(result.next()) {
for(var i=0; i<23; i++) { // four fields per record
cell.offset(row, i).setValue(result.getString(i+1));
}
row++;
}
result.close();
SQLstatement.close();
conn.close();
}
This Google Script is only putting about 150 rows into my Google Sheet and then it times out.
Can someone help me find a fix for this?
Something like this:
function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
let oA=[];
sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).clearContent();//clear content before writing
while(result.next()) {
let rA=[];
for(var i=0; i<23; i++) {
rA.push(result.getString(i+1));
}
oA.push(rA);
}
sheet.getRange(2,1,oA.length,oA[0].length).setValues(oA);//starts at row 2 every time
result.close();
SQLstatement.close();
conn.close();
}

Send email notification using multiple sheet tabs when a cell value change

Below function works well but I want to add 2nd sheet which have same number of columns and rows. The logic is the same when user select 'Yes' in column 7. How do I get to send email if user select 'yes' in Sheet2. I did create duplicate function and name sheet as 'Sheet2'. When I click 'Yes' in Sheet2, I get a email notification for Sheet1 and Sheet2 even though Sheet1 is not selected 'Yes'. If user select 'Yes' in Sheet1, it should only get email from Sheet1 and likewise in Sheet2. How do I go about it?
function sendNotification(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var editedRange = e.range;
if(sheet.getName()=='Sheet1' && editedRange.getColumn()==7 && e.value=='Yes'){
var row = editedRange.getRow();
var numRows = sheet.getLastRow()-1;
var row_values = sheet.getRange(row, 1, numRows, 7).getValues()[0];
var first_name = row_values[0];
var last_name = row_values[1];
var company = row_values[3];
var email= row_values[5];
var message = "The person has completed Sheet1"+first_name+" "+last_name+ " -
"+company;
var subject = "Completed - "+first_name+" "+last_name;
MailApp.sendEmail(email, subject, message);
}
}
Replace
var sheet = ss.getSheetByName('Sheet1');
by
var sheet = e.range.getSheet();
and replace
if(sheet.getName()=='Sheet1' && editedRange.getColumn()==7 && e.value=='Yes'){
by
if(['Sheet1', 'Sheet2'].indexOf(sheet.getName()) > -1 && editedRange.getColumn()==7 && e.value=='Yes'){
['Sheet1', 'Sheet2'].indexOf(sheet.getName()) will return 0 or 1 if sheet.getName() returns 'Sheet1' or 'Sheet2', respectively and -1 in any other case.
NOTE: You can remove var ss = SpreadsheetApp.getActiveSpreadsheet();

Google Sheets - post DATE and USERNAME who edited it

This code works on Google Sheets as to:
Help users update today's date in a column, and effectively add a signature.
In a specific column, users type in any random jibberish (easy to do), and the sheet will then change this to today's date, and add their logged-in email address as a signature.
Ps the sheet does know who's currently logged in - I've set the sheet so users do have to be logged in and given access to the sheet
This is my code (https://imgur.com/8KSBbsB):
function onEdit(event)
{
var timezone = "UTC";
var timestamp_format = "d/MM/yy"; // Timestamp Format.
var updateColName = "[code]";
var timeStampColName = "[code]";
var nameColname = "[codename]";
var userName = Session.getEffectiveUser().getEmail();
var sheet = event.source.getSheetByName('Rank Sheet'); //Name of the sheet where you want to run this script.
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var nameCol = headers [0].indexOf(nameColname); nameColname = nameColname+1;
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date + " " +userName)
var cell = sheet.getRange(index, nameColname + 1);
var nameCol = cell.setValue = (userName)
}
}
To do this you need to 'title' the columns [code], and [codename] (changeable).
Thank you very much to Cooper for advice given!!
Try this:
cell.setValue(date + '\n' + userName)

Script to search a column for a value and return the row number to use in a variable

I have a code I use to send email reminders based on dates in a spreadsheet. Most of the sheets I use it for are simple and under 100 lines of data. In the past I have used individual variables for each cell but I am looking for a way to find all instances of a value in a column (D), in this case, it is a city code ("SEA"), and return the row number, which I then want to take and use in a var to make it act like a vlookup.
ex: var empname = ss.getRange("A"+ rownumber).getValue();
Which should return column A of whichever row has "SEA" in it.
The challenge then is to be able to go down the column and do the same for each row that has "SEA" in it.
This is a one-line version of what I have done in the past.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var ss = spreadsheet.getSheetByName("Active");
var empnum = ss.getRange("A8").getValue();
var empfirstname = ss.getRange("C8").getValue();
var emplastname = ss.getRange("B8").getValue();
var emplocation = ss.getRange("D8").getValue();
var test = ss.getRange("H8").getValue();
if (test === -1 && emplocation === "SEA"){
var message = empnum + " " + empfirstname + ' ' + emplastname + ' is past due for testing.' + '\n'
} else if (test === 0 && emplocation === "SEA"){
var message = empnum + " " + empfirstname + ' ' + emplastname + ' will be due for testing soon.' + '\n'
} else if (test === 1) {
var message = "";
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email Group").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Test reminder';
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + 'Test reminder:\n\n' + message + '\n\n**This is an automated message**\n');
}
The H column will present a -1, 0 or 1 depending on the date in the G column to determine if someone is due to take a test or not. I then want to send an email with the Employee Number, First Name and Last Name for each employee at the SEA branch. This has worked for me in the past but I have 230+ lines of employees and don't want to create that many variables. My solution is to get the row number of each row with a "SEA" location and use that as a variable in a getRange call. Not sure exactly how that would work, or if it even would. If there is a better solution, I am amenable to that.
Requirement:
Send an email when a row contains "SEA" and column H matches -1 or 0.
Solution:
function findAndSendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Active');
//find all occurrences of "SEA" and push range to array
var search = "SEA";
var ranges = ss.createTextFinder(search).findAll();
var message = ''; //pre-define email body
//loop through each range
for (i = 0; i < ranges.length; i++) {
var row = ranges[i].getRow();
var lastCol = ss.getLastColumn();
var values = ss.getRange(row, 1, 1, lastCol).getValues(); //get all values for the row
var empnum = values[0][0]; //column A
var empfirstname = values[0][2]; //column C
var emplastname = values[0][1]; //column B
var emplocation = values[0][3]; //column D
var test = values[0][7]; //column H
if (test === -1) {
message+=Utilities.formatString(empnum + " " + empfirstname + ' ' + emplastname + ' is past due for testing.\n');
} else if (test === 0) {
message+=Utilities.formatString(empnum + " " + empfirstname + ' ' + emplastname + ' will be due for testing soon.\n');
}
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email Group").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Test reminder';
if (message) { //make sure message is not blank
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + 'Test reminder:\n\n' + message + '\n\n**This is an automated message**\n');
}
}
Explanation:
Okay, so I've made quite a few changes to your original script, if there's anything I've missed please let me know, I'm happy to explain it.
First of all, I've changed the script so that we're using textFinder, this is so that we can search through your sheet to find your desired pattern "SEA". This then pushes all of the ranges to an array that we are looping through in the for loop.
When looping through the ranges, we can grab all of the data in the row (e.g. values[0][0] is the data in column A). This is then pushed to var message to build the email body in the same format you specified in your question.
I've tried to keep the variable names alike to the ones in your original script to make it easier to understand which parts of the script are essentially the same as your original. Also there are comments throughout the script that should help you understand what it's doing at each point.
References:
textFinder Documentation
Update:
To scan only a certain column, try the code below instead. I've defined var range separately so that we can use textFinder on that range rather than the whole sheet.
function findAndSendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Active');
//define range to search
var lastRow = ss.getLastRow();
var range = ss.getRange(1, 4, lastRow); //range for column D
//find all occurrences of "SEA" in column D and push range to array
var search = "SEA"
var ranges = range.createTextFinder(search).findAll();
var message = '';
//loop through each range
for (i = 0; i < ranges.length; i++) {
var row = ranges[i].getRow();
var lastCol = ss.getLastColumn();
var values = ss.getRange(row, 1, 1, lastCol).getValues(); //get all values for the row
var empnum = values[0][0]; //column A
var empfirstname = values[0][2]; //column C
var emplastname = values[0][1]; //column B
var emplocation = values[0][3]; //column D
var test = values[0][7]; //column H
if (test === -1) {
message+=Utilities.formatString(empnum + " " + empfirstname + ' ' + emplastname + ' is past due for testing.\n');
} else if (test === 0) {
message+=Utilities.formatString(empnum + " " + empfirstname + ' ' + emplastname + ' will be due for testing soon.\n');
}
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email Group").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Test reminder';
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + 'Test reminder:\n\n' + message + '\n\n**This is an automated message**\n');
}
}