How can I edit Google Spreadsheets Cells using the API? - google-apps-script

I have a form and an API a Google Apps Script attached to it.
After sending the form I want to confirm that the script ran successfully with no errors by adding a value V to the last column of the form response's spreadsheet.
But I can't find any way to edit an existing row. Can someone help me with that?
Additional information from comments:
var responsesSSID = SpreadsheetApp.openById('*****************');
var values = responsesSSID.getDataRange().getValues();
values[values.length-1][values[].length-1] = "V";
I couldn't find anything here (for the next line) that will work.

Assuming that you want to update/edit the last column of the last row of your spreadsheet :
var sprdkey = '0Ai4sb45QfOAQdGhRWEtQaTR0enVHUHlxSTlobkVtenc';
var sheet = SpreadsheetApp.openById(sprdkey).getActiveSheet();
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
sheet.getRange(lastRow , lastCol).setValue("V");
If you need to edit any other cell in the spreadsheet, you just need to pass the appropriate parameters to the getRange(row_no, col_no) function.
Hope this helps!

Related

How to find value from Google sheet using multiple cell values and send email

I want to find the particular values in a google sheet, once its found then fetch total row values and send email from google sheet with the total row values.
I'm aware of send email from google-sheet but finding the particular value based on that send email is very challenging for me.
Wherever E60 is present the should fetch total row values and need to send email.
To send a email via google sheet you will need to write some code with script editor. I think you could find more details here
After studying your question, I assume the following:
You want to check a column matching the string E60.
When a cell with E60 is found, your want to send a email with the full row content.
If my assumptions are correct, you can use the following example to fulfill your requests:
CODE
function E60Alert() {
var sheet = SpreadsheetApp.openById(
'{SPREADSHEET ID}').getSheetByName('Sheet1');
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var subject = "E60 Alert";
var email = "{YOUR EMAIL}";
var rowContent = sheet.getRange(1, 1, lastRow, lastColumn).getValues();
for (var i = 1; i <= lastRow; i++) {
if (rowContent[i - 1][4] == 'E60') {
MailApp.sendEmail(email, subject, rowContent[i - 1]);
}
}
}
BEHAVIOUR
That code will first read the full table. After that, it will iterate it searching for the desired string (E60 in this case). If it finds it, it will send an email with the full row content.
OBSERVATIONS
This code will run on demand by clicking the Run button.
You will have to edit the if (rowContent[i - 1][4] == 'E60') { line to match the desired column of the data. I chose the fifth column (number 4) for testing purposes.
ALLUSIONS
getLastRow() & getLastColumn()
getRange() & getValues()
sendEmail()
Please take this as one of the possible solutions to your issue, and don't hesitate to write me back with any additional doubts or requests to further clarifications.

Can I add a formula to a google form response using Apps Script?

Apologies as I am a beginner to coding. I am interested in using Google Apps Script to automate the analysis of a Google Form response.
The simple example I have is for the spreadsheet of responses for a form asking people:
1) how many players there were?
2) where they finished [1st, 2nd, etc,]
On submission of the form I want to run a script that calculates how may points they received and inserts this value in the next available column (column E in this example).
I have tried writing my first Apps Script to automate this process, but without success.
SAMPLE CODE:
function onFormSubmit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses Master");
var players = e.values[2];
var place = e.values[3];
var positionPoints = e.values[4];
var positionPoints = (players - place + 1);
return positionPoints;
}
I know there are workarounds available by creating duplicate pages, but I was hoping someone might be able to advise me on how to code a solution in App Scripts, in the hope I might get a better understanding of the coding process.
You can write your appscript in the response collector spreadsheet itself instead of writing your code in form's script editor.
So, go to your response sheet and paste this code.
function myFunction()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses Master");
var rowNo = sheet.getLastRow();
var colNo = sheet.getLastColumn();
sheet.getRange(rowNo, colNo).setValue("=(C"+rowNo+"-D"+rowNo+")+1");
}
Now, go to Resources -> Current project triggers. Click on add new and set these values in drop downs: myFunction - From Spreadsheet - On form submit.
And you are done. Whenever a new response is submitted, position points will be calculated automatically.
Here,
variable sheet gets your active spreadsheet for different sheet operations which you can perform.
rowNo and colNo as seen in the code, simply fetches the value of last row/column respectively of spreadsheet in which something is written.
And, to set formula in column 'E', you can use setValue. Hence, "=(C"+rowNo+"-D"+rowNo+")+1" will be converted to (C2-D2)+1 in case of second row and so on for next rows.
getRange is simply used to tell the script that write formula inside particular cell.

google apps script - paste in next empty row

with google apps script I am collecting data from the google analytics API.
This is set to collect data every night 1 am for the previous day and writing that in to a sheet “original”
In my second script I want to copy a range A1:G1 from the sheet “original” to my second sheet “copy”
And what I want is continuously to copy the data to the next empty row, but how?
So far I have this as a basic solution, but this is always pasting the selected data into the defined cell (in this case cell A10)
function copytestdata() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("original");
var sheet2 = ss.getSheetByName("copy");
sheet1.getRange("A1:G1").copyTo(sheet2.getRange("A10"), {contentsOnly:true});
}
I would like a dynamic solution on the second sheet “copy”.
So new data should be pasted in to the next empty row starting from cell A1 and the go down to next empty row.
But how do I get the script to go down to the next empty row?
sheet1.getRange("A1:G1").copyTo(sheet2.[DYNAMIC SOLUTION]), {contentsOnly:true});
Have anyone got a brilliant idea? I would really appreciate the help.
Ohh and by the way how can I actually go to a specific cell sort of like:
sheet1.getActiveRange(“B8”)
Thanks a lot in advance for your help
Pelikan76
why not using getLastRow()+1 ?
function copytestdata() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("original");
var sheet2 = ss.getSheetByName("copy");
sheet1.getRange("A1:G1").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
}

Writing variables to the next available spreadsheet row in a Google Apps Script

Quick question: I am a newbie to Google Apps Script, and want to do something really simple. I have a spreadsheet where I would like to log my results every time the script runs. Let's say I have three variables, and each time I execute, I want to go to the first available empty row in the sheet, and assign variable #1 to Column A, variable #2 to Column B, etc. I'm guessing there's all types of examples where that kind of thing happens every day. Can someone point me to such an example?
Thanks for your help.
TomC
maybe this way is better or at least shorter:
var logSheet = SpreadsheetApp.openById(logSpreadsheetId).getSheets()[0];
logSheet.appendRow([var1, var2, var3]);
In your Google Apps Script, you will want to look at something called sheet.getLastRow()
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// This logs the value in the very last cell of this sheet
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var lastCell = sheet.getRange(lastRow, lastColumn);
Logger.log(lastCell.getValue());
Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow()

Google Script: Conditionally copy rows from one sheet to another in the same spreadsheet

I read Google Script: Conditionally copy rows from one spreadsheet to another and could not make it work for me.
I need a script that will allow me to do the quoted text below. Please feel free to edit my spreadsheet to make a complete working script. I will keep the spreadsheet publicly available for anyone to copy the script for their own use. I really know nothing about script writing so I need it all spelled out. Sorry, I'm such a noob with all this, but this will help me learn.
https://docs.google.com/spreadsheet/ccc?key=0AoJdwy8V1ldHdFA5M1M1Wlp1NHZhcmxJOUZKVEU4X3c&usp=sharing
If Column B on sheet "All_Mileage" says "John" then I want that row to
be copy and pasted into Sheet "John" starting on row 3 and following.
If Column B on sheet "All_Mileage" says "Adam" then I want that row to
be copy and pasted into Sheet "Adam" starting on row 3 and following.
If Column B on sheet "All_Mileage" says "Mike" then I want that row to
be copy and pasted into Sheet "Mike" starting on row 3 and following.
I saw other scripts on here, but I couldn't get them to work. Like I said I'm greener than a sapling when it come to code.
Thanks a ton!
C.Lang is right, this is not a place to get readymade scripts ... but since this question is so common and has been aswered so often it took me a few minutes to write and test... so there it is :
var ss=SpreadsheetApp.getActiveSpreadsheet();// some global variables
var master = ss.getSheetByName('All_Mileage');
var colWidth = master.getMaxColumns();
function copyRowsOnCondition() {
var data = master.getDataRange().getValues();
for(n=2;n<data.length;++n){
if(data[n][1].length<16){ // if not pre-filled with your text
Logger.log(data[n][1])
var dest = ss.getSheetByName(data[n][1].toString().replace(/ /g,''));//remove any spaces that could be included in the name so the name = sheetName for sure
var destRange = dest.getRange(dest.getLastRow()+1,1);// the place to write
master.getRange(n+1,1,1,colWidth).copyTo(destRange);the copy itself value & format
}
}// loop
}
EDIT : since I used the name value in MasterSheet to find destination sheet I thought it might be usefull to handle the case where the destination sheet doen't exist by creating it using the same rule, ie. name = sheetName...
The other issue was that there was no way to know which rows had been already copied... so I made a version that handles all that, copying only the rows that are manually selected (even in only a single column) and change the background color to tell that these rows have been processed. I also added a menu for a minimal comfort ;-)
(how to keep busy on a cold sunday afternoon ;-)
var ss=SpreadsheetApp.getActiveSpreadsheet();
var master = ss.getSheetByName('All_Mileage');
var colWidth = master.getLastColumn();// last used col in masterSheet
var sheets = ss.getSheets();// number of sheets
function onOpen() {
var menuEntries = [ {name: "Copy selected Rows to sheets", functionName: "copyRowsOnConditionV2"},
];
ss.addMenu("Copy functions",menuEntries);// custom menu
}
function copyRowsOnConditionV2() {
var sheetNames = [];// array of existing sheet names
var sheets = ss.getSheets();// number of sheets
for(s=0;s<sheets.length;++s){sheetNames.push(sheets[s].getName())};
ss.getActiveSelection().setBackground('#ffffbb');
var selectedfirstRow = ss.getActiveSelection().getRowIndex();
var selectedHeigth = ss.getActiveSelection().getHeight()
var selectedFullRange = master.getRange(selectedfirstRow,1,selectedHeigth,colWidth);
var data = selectedFullRange.getValues();
for(n=0;n<data.length;++n){
if(data[n][1].length<16){
if(sheetNames.toString().match(data[n][1].toString().replace(/ /g,''))!=data[n][1].toString().replace(/ /g,'')){// if no sheet exist with this name
var newSheet = ss.insertSheet(data[n][1].toString().replace(/ /g,''),ss.getSheets().length);// then create it
master.getRange(1,1,2,colWidth).copyTo(newSheet.getRange(1,1));// and copy the headers on 2 first rows, then continue as usual
newSheet.getRange(1,1).setValue('Gas Mileage Log - '+data[n][1].toString().replace(/ /g,''));// set name in header
SpreadsheetApp.flush();
var sheets = ss.getSheets();// number of sheets
var sheetNames = [];// update array of existing sheet names
for(s=1;s<sheets.length;++s){sheetNames.push(sheets[s].getName())};
Logger.log(sheetNames)
};
var dest = ss.getSheetByName(data[n][1].toString().replace(/ /g,''));//find the destination sheet
Logger.log(data[n][1].toString().replace(/ /g,''))
var destRange = dest.getRange(dest.getLastRow()+1,1);// define range
master.getRange(selectedfirstRow+n,1,1,colWidth).copyTo(destRange);// and make copy below last row
}
}
}
Illustration below :