Apps script - google sheet ,need a help in user form - google-apps-script

I'm working on an apps script for my google spreadsheet. In that, I want a search feature that will search in data and brings back it to the user form for updating. I did code with no error but still, the output is not completed. Please help me with this guys!!
this is the code-
var SEARCH_COL_IDX = 0;
function search() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var e = ss.getSheetByName("ENTRY"); //Form Sheet
var str = e.getRange("G7").getValue();
var values = ss.getSheetByName("DATA").getDataRange().getValues();
for (var i = 2; i < values.length; i++) {
var row = values[i];
if (row[SEARCH_COL_IDX] == str) {
e.getRange("D6").setValue(row[0]);
e.getRange("H4").setValue(row[1]);
e.getRange("D4").setValue(row[2]);
e.getRange("D7").setValue(row[3]);
e.getRange("D8").setValue(row[4]);
e.getRange("D12").setValue(row[5]);
e.getRange("D13").setValue(row[6]);
e.getRange("D14").setValue(row[7]);
e.getRange("D15").setValue(row[8]);
e.getRange("D16").setValue(row[9]);
e.getRange("H12").setValue(row[10]);
e.getRange("H13").setValue(row[11]);
e.getRange("H14").setValue(row[12]);
e.getRange("H15").setValue(row[13]);
e.getRange("H16").setValue(row[14]);
e.getRange("H17").setValue(row[15]);
} }}

Related

Get url of the google form every time after submission is done

I am using a google script to get the url of the Google form successfully to Google spreadsheets. However, I must manually click run in google script in order to get the url.
How to get the url automatically when someone click the submit button in Google form?
Below is the code of my script
function assignEditUrls() {
var form = FormApp.openById('1F4YdKMGlJXn9w8aiq0UXzegWEfzjxUMd2CV2vewmoLQ');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses 1');
var data = sheet.getDataRange().getValues();
var urlCol = 37;
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
I also have set the project triggers to on form submit
However, I still can't automatically get the url of the google form even submitted. I have to manually click run the script in order to get the url in spreadsheet
To use the "on form submit" spreadsheet trigger, you need to first make sure that the form is saving responses to that spreadsheet. You can then use the event object to replace some of the literal values you've declared.
Unfortunately, the trigger doesn't provide the response ID, so you'll need to manually search for it using the provided timestamp.
function assignEditUrls(e) {
var sheet = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
var ts = new Date(e.namedValues.Timestamp[0]);
var form = FormApp.openById("1F4YdKMGlJXn9w8aiq0UXzegWEfzjxUMd2CV2vewmoLQ");
var formResponses = form.getResponses(ts);
var editURLColumn = 37;
var row = e.range.getRow();
for (var i = 0; i < formResponses.length; i++) {
var formResponseTs = (new Date(formResponses[i].getTimestamp())).getTime();
if (formResponseTs === ts.getTime()) {
var responseId = formResponses[i].getId();
var editURL = formResponses[i].getEditResponseUrl();
sheet.getRange(row, editURLColumn).setValue(editURL);
break;
}
}
}

Google App Script - getCommenter

I'm brand new to Google Apps Script, and I'm trying to create a simple spreadsheet that will allow me to share files by user email through a single spreadsheet.
I have written the following script, which will allow me to add editors and viewers, but not commenters.
I keep getting an error that states that the function addCommenter cannot be found in object spreadsheet.
function shareSheet () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast('Updating access level...');
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var range1 = sheet.getRange (3,1, lastRow,9);
var data = range1.getValues();
for (var i= 0; i < data.length; i++) {
var row = data [i];
var accessLevel = row [5];
var values = row [8];
var ss2 = SpreadsheetApp.openById(values);
var values2 = row [4];
// Add new editor
if (accessLevel == 'Edit') {
var addEditors = ss2.addEditor(values2);
}
// Add new viewer
if (accessLevel == 'View'){
var addViewers = ss2.addViewer(values2);
}
// Add new commenter
if (accessLevel == 'Comment') {
var addCommenters = ss2.addCommenter(values2);
}
}
}
The Spreadsheet object does not support the addCommentor() method. You should use DriveApp service instead.
DriveApp.getFileById(id).addCommenter(emailAddress)

How to import contact names from emails in Gmail to Google Sheets?

I have inherited a Google apps script (see below) used in Google sheets to import email data using a Gmail search label. The script works to a degree, but is failing to extract the first and second names from the emails.
I searched the GmailApp documentation but I cannot find anything about importing names, only their email addresses. I know this script used to be able to extract the names, so did Google remove this functionality or am I missing something?
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var clear = [ {name:"Clear Sheet", functionName: "clearSheet"} ];
var menu = [ {name: "Import selected emails", functionName:
"selectedEmails"},];
sheet.addMenu("Import Emails", menu);
sheet.addMenu("Clear Sheet",clear);
sheet.toast("To get started click on 'Import Emails' option on the
menubar.", "Ready", 7);
}
function selectedEmails(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var query=Browser.inputBox("Enter your Gmail search query","",Browser.Buttons.OK_CANCEL);
var lastEntry=2;
var oldPercentage=0;
if(query!="" && query!="cancel"){
var threads = GmailApp.search(query);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var subject = messages[j].getSubject();
var student_num = studentNum(subject);
sheet.getRange("A"+lastEntry).setValue(student_num);
sheet.getRange("B"+lastEntry).setFormula("vlookup(A" + lastEntry + ",ids!A:C,2,0)");
sheet.getRange("B"+lastEntry).setValue(sheet.getRange("B"+lastEntry).getValue());
sheet.getRange("C"+lastEntry).setFormula("vlookup(A" + lastEntry + ",ids!A:C,3,0)");
sheet.getRange("C"+lastEntry).setValue(sheet.getRange("C"+lastEntry).getValue());
sheet.getRange("D"+lastEntry).setValue(subject);
if(i/threads.length*100-oldPercentage>4){
oldPercentage=i/threads.length*100;
sheet.toast(i/threads.length*100+"% completed", "In Progress", 3);
}
lastEntry+=1;
}
}
sheet.autoResizeColumn(1);
sheet.autoResizeColumn(2);
sheet.autoResizeColumn(3);
sheet.autoResizeColumn(4);
sheet.autoResizeColumn(5);
sheet.toast("Export completed successfully", "Done", 3);
}
}
function clearSheet(){
//clear the used rows
var mysheet = SpreadsheetApp.getActiveSpreadsheet();
var lastRow = mysheet.getLastRow();
/*
if(lastRow>0){
mysheet.insertRowAfter(lastRow);
mysheet.getRange("A1:E"+lastRow).clear();
}
for(i=lastRow;i>0;i--){
mysheet.deleteRow(i);
}
*/
mysheet.deleteRows(2, LastRow);
//Initialize the header
mysheet.getRange("A1").setValue("ID");
mysheet.getRange("B1").setValue("Surname");
mysheet.getRange("C1").setValue("Forename");
mysheet.getRange("D1").setValue("Subject");
mysheet.getRange("E1").setValue("Result");
mysheet.getRange("A1:E1").setBackground("#bbed95");
mysheet.getRange("A1:E1").setFontSize(14);
mysheet.getRange("A1:E1").setHorizontalAlignment("center");
//Initialize the header
}
//function to extract Student Numbers
function studentNum(text){
var pattern=/[0-9]{8}/;
var snum = text.match(pattern)*1;
return snum;
}
Found it. Wasn't called what I expected it to be called.
getFrom()

Time driven function in Google script

I am trying to download the data from a website every hour using Google script. The code is shown as below. When I manually run the function CSV_sgj, I can receive the desired information in email. But when I set the function as time driven (every hour), what I get are all #VALUE!.
I found a similar question and tried to change
var sheet = SpreadsheetApp.getActiveSheet();
to
var sheet = SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");
but it still does not work.
Many thanks in advance for help!
The full code is below.
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
/**
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
*/
function CSV_sgj() {
readRows();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:N32");
var data = range.getValues();
var csv = "";
for (var i = 0; i < data.length; ++i) {
csv += data[i].join(",") + "\r\n";
}
var csvFiles = [{fileName:"PSI5.csv", content:csv}]
MailApp.sendEmail("xxxxxx#gmail.com", "CSV", "", {attachments: csvFiles});
}
When you use
var sheet = SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");
the returned value is a spreadsheet object and what you want is a sheet object...
So you have to get the sheet by its name or by its index number. I suggest you change the variable names accordingly to keep things clear :
var ss= SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");
var sheet = ss.openByName('sheet1');// or any name you use (a string)
//or by its index
var sheet = ss.getSheets()[0] ;// 0 is the index of the first sheet in the spreadsheet (integer)

Need help creating For loop in Script editor to make Script run code on all sheets in a Google Spreadsheet

I have a script that I am trying to run on all sheets within a google doc and dont know how to make that work. IT works for one sheet, but I have numerous sheets all with the same format that need to be checked. Thanks.
Here's the script I am trying to apply to all sheets.
function sendEmail(email_address, email_subject, email_message) {
MailApp.sendEmail(email_address, email_subject, email_message);
}
function timestamp() {
return new Date()
}
var EMAIL_SENT = "EMAIL_SENT";
function test_sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.setActiveCell('A2');
var criterion_cutoff = 5;
var i = 0;
var startRow = 2;
var addr;
var subj;
var msg;
var timecheck
do {
addr = cell.offset(i,0).getValue();
subj = cell.offset(i,1).getValue();
msg = cell.offset(i,2).getValue();
criterion = cell.offset(i,3).getValue();
timecheck = cell.offset(i,11).getValue();
if (timecheck > 0) {
if(criterion < criterion_cutoff) {
sendEmail(addr,subj,msg);
Browser.msgBox('Sending email to: ' + addr);
}}
i++;
} while( cell.offset(i, 0).getValue().length > 0 )
sheet.getRange(2, 5).setValue(timestamp());
Browser.msgBox('Done!');
}
You can use an array of IDs that you want to apply the script to by making the following changes:
1. Change
function test_sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
to:
function test_sendEmail(sheetID) {
var sheet = SpreadsheetApp.openById(sheetID);
2 . Define an array of IDs of sheets that you want to change:
var idArray = [Spreadsheet1_id, Spreadsheet2_id, ...];
3 . create a loop that would cycle through all the elements of the array
for(var k in idArray) test_sendEmail(idArray[i]);
If you don't want to manually populate the idArray, you can create a function that would pull IDs of all spreadsheets in your Google Drive. If that is what you want, then use the following code instead of the line of code I provided you with in point 2.
var sprArr = DocsList.getFilesByType("spreadsheet");
var idArray;
for(var k in sprArr) idArray.push(sprArr[i].getId());