How do I find the data in a column within an active row that is already defined in Google Apps Script?
I have an on edit function that sends an email when a column f is edited to a specific value. I need to find out the value in column b in order to include the value in the body of the message.
I have tried to use a range, but I am not understanding how i can define the second column for the active range that is already defined in the row variable. Here is what my code looks like. var called Values is the row of code I need help with. The row var is looking at the correct row. Any help is greatly appreciated.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var cell = sheet.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = sheet.getActiveCell().getValue().toString();
var values = row.getcell()[0,2].getvalue().toString();
var recipients = "kel...#trafficbuilders.us";
var message = '';
if(cellvalue === '✔'){
message = 'All Items have been received for .';
var subject = 'All Items have been received for ' ;
var body = message + ' Visit ' + ss.getUrl() + ' to view the changes';
MailApp.sendEmail(recipients, subject, body);
}
}
To fetch a certain data/value from a certain cell, here's what you can do:
First identify the cell where data is located using getRange(). There are several ways to use getRange.
Sample from the docs:
// Get a range A1:D4 on sheet titled "Invoices"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("Sheet!A1:D4");
// Get cell A1 on the first sheet
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("A1");
To actually fetch the content/data, use getValues() or getValue()
sample snippets:
// The code below gets the values for the range C2:G8
// in the active spreadsheet. Note that this is a JavaScript array.
var values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getValues();
Logger.log(values[0][0]);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Passing only two arguments returns a "range" with a single cell.
var range = sheet.getRange(1, 1);
var values = range.getValues();
Logger.log(values[0][0]);
Related
I am trying to write a script to copy a range of cells to cell B2. The range to copy from changes each time so want to highlight the top left cell and then the script takes it from there. What I have so far is:
function CopyToB2() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
var selectedColumn = cellRange.getColumn();
var selectedRow = cellRange.getRow();
var range = SpreadsheetApp.getActiveSheet().getRange(selectedColumn,selectedRow,2,43);
range.setValues(range);
spreadsheet.getRange('B2').activate();
(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};
but get the error
Exception: The parameters (SpreadsheetApp.Range) don't match the
method signature for SpreadsheetApp.Range.setValues
Explanation:
The main issue with your code is that you pass a range object in the setValues function and therefore you are getting this error.
A second issue is that you passed the parameters of the getRange(row, column, numRows, numColumns) function in the wrong order. It should be:
getRange(selectedRow,selectedColumn,43,2)
instead of getRange(selectedColumn,selectedRow,2,43)
A third issue is that you need to define the range that the data will be pasted to and that can't be just a single cell B2 in this case. What you need to do is to define B2 as the start of your pasting range and then set the values of your active range.
Solution:
function CopyToB2() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
var selectedColumn = cellRange.getColumn();
var selectedRow = cellRange.getRow();
var dataRange = sheet.getRange(selectedRow,selectedColumn,43,2).getValues();
sheet.getRange(2,2,dataRange.length,dataRange[0].length).setValues(dataRange);
};
How do I get the new input values in google sheet using App Script. I currently get the values when I specify which cells, but I want it to be dynamic. Please help me.
function getValuesinSheet(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.getRange("B1").setValue("Email");
sheet.getRange("A1").setValue("Amount");
sheet.getRange("C1").setValue("Phone Number");
sheet.getRange("D1").setValue("Email Subject");
sheet.getRange("E1").setValue("Message");
var amount = parseInt(sheet.getRange("A2").getValues()) ;
var email = String(sheet.getRange("B2").getValues());
var snumber = String(sheet.getRange("C2").getValues());
var esubject = String(sheet.getRange("D2").getValues()) ;
var emessage = String(sheet.getRange("E2").getValues());
}
(Option 1)
You can use onEdit Simple Trigger, to execute an apps script function every time a cell is being modified to read/modify your sheets.
Sample Code:
function onEdit(e){
var ss = e.source; //Get the spreadsheet
var cell = e.range; //Get the range of the edited cell
var sheet = ss.getActiveSheet(); //Get the modified sheet
var row = cell.getRow();
var col = cell.getColumn();
//valid cell are within A2:E. If row ==1 or col > 5 do nothing
if(row==1 || col > 5){
return;
}
//Get the current row's first 5 columns
//Change 2-d array to 1-d array using flat()
var rowValues = sheet.getRange(row,1,1,5).getDisplayValues().flat();
if(rowValues.filter(String).length == 5){
Logger.log("DO SOMETHING")
var amount = parseInt(rowValues[0]);
var email = rowValues[1];
var snumber = rowValues[2];
var esubject = rowValues[3];
var emessage = rowValues[4];
Logger.log(amount);
Logger.log(email);
Logger.log(snumber);
Logger.log(esubject);
Logger.log(emessage);
}
}
What it does?
Get the active sheet and active cell using the onEdit() events object
Get the active cell's row and column index (apps script used one-based as index)
Check if modified cell is within A2:E range, by checking row and column index
Get the current row values from column A:E using Sheet.getRange(row, column, numRows, numColumns) and Range.getDisplayValues()
I used Range.getDisplayValues(), since it will return a 2-d array of string. I noticed that you expect your inputs as a string and you plan to convert the amount to int using parseInt()
Use flat() to convert 2-d array to 1-d array
Check the array if all the columns are not empty using filter(), if array length is 5. Then all data in the row is complete
Note:
You can remove the condition in Step 6 if you want to process the current row's column A-E values even if some data are empty.
You can also remove the condition in Step 3 based on your preference. I just included that so that the succeeding process will only be executed when cell being modified are within A2:E
Additional Information
If you are new with Simple Triggers, you cannot debug your code by running it in the Apps Script Editor. If you want to debug your code, you need to modify a specific cell in your sheet then check the latest logs in the Executions tab.
Example:
(Option 2)
If you don't prefer to use onEdit() Simple trigger. You can just use getActiveCell() to get the current selected cell row and column index
Sample Code:
function getRowValues(){
var ss = SpreadsheetApp.getActiveSpreadsheet(); //Get the spreadsheet
var cell = ss.getActiveCell(); //Get the range of the edited cell
var sheet = ss.getActiveSheet(); //Get the modified sheet
var row = cell.getRow();
var col = cell.getColumn();
//valid cell are within A2:E. If row ==1 or col > 5 do nothing
if(row==1 || col > 5){
return;
}
//Get the current row's first 5 columns
//Change 2-d array to 1-d array using flat()
var rowValues = sheet.getRange(row,1,1,5).getDisplayValues().flat();
if(rowValues.filter(String).length == 5){
Logger.log("DO SOMETHING")
var amount = parseInt(rowValues[0]);
var email = rowValues[1];
var snumber = rowValues[2];
var esubject = rowValues[3];
var emessage = rowValues[4];
Logger.log(amount);
Logger.log(email);
Logger.log(snumber);
Logger.log(esubject);
Logger.log(emessage);
}
}
I want to know if we can select a row in a Spreadsheet using Google script like this
Anyway first I've tried with the columns by using this fonction but I get an error of the data (is not found): If you have an idea :)
function testGetFullColumn()
{
getFullColumn('A', 1) ;
}
// This function gets the full column Range like doing 'A1:A9999' in excel
// #param {String} column The column name to get ('A', 'G', etc)
// #param {Number} startIndex The row number to start from (1, 5, 15)
// #return {Range} The "Range" object containing the full column: https://developers.google.com/apps-script/class_range
function getFullColumn(column, startIndex){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var lastRow = sheet.getLastRow();
return sheet.getRange(column+startIndex+':'+column+lastRow);
}
Edit :I know about getRange but I would be cool^^^^^^ to see in visually the selection like in the photo I've attached because I tried with
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; return sheet.getDataRange();
and it doesn't select all the sheet visually I mean I want to see an interactive selection :) like here
Edit 2: I've tried to use setActiveRange after getRange as you suggested thanks Guilherme M but it doesn't select visually all the document :( Your code works it's really cool^ I was afraid that it's impossible to select I will try to do the same thanks ^^
function testGet()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getDataRange();
SpreadsheetApp.setActiveRange(range)
}
Edit 3: To select all the document I've tried this code:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var range = sheet.getRange(1,1,lastRow+1,lastColumn+1);
sheet.setActiveRange(range);
var selection = sheet.getSelection();
// Current cell: A1
var currentCell = selection.getCurrentCell();
// Active Range: tout le document
var activeRange = selection.getActiveRange();
Yes, you can select a row or any range in the spreadsheet using Apps Script. You do so with method setActiveRange(). An example follows below:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange('A1:D4');
sheet.setActiveRange(range);
var selection = sheet.getSelection();
// Current cell: A1
var currentCell = selection.getCurrentCell();
// Active Range: A1:D4
var activeRange = selection.getActiveRange();
Notice The method getDataRange() selects range "in which data is present.", so it won't select blank cells or the whole document. For such task, you need method getRange(row, column, numRows, numColumns) combined with getMaxRows() and getMaxColumns().
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
sheet.setActiveRange(range);
var selection = sheet.getSelection();
// Current cell: A1
var currentCell = selection.getCurrentCell();
// Active Range: A1:D4
var activeRange = selection.getActiveRange();
To do that you show in the image i use this:
function myFunction2() {
SpreadsheetApp.getActive().getRange( 2 + ':' + 2 ).activate();
};
and if you want to make it variable so, add a variable like n:
function myFunction2() {
var n = 2
SpreadsheetApp.getActive().getRange( n + ':' + n ).activate();
};
the way to manage range, rows and columns, are in the other answer.
I want to take the last response from a Google Form and copy it to the same range on another sheet.
The second sheet has some data in columns A & B (a login and password) that I want to assign as somebody completes the registration form.
I want the data from column B to H from the form response sheet to be copied to column C to I on the sheet that contains the login/password columns when a response is received.
I know I am missing the code to take the range from the last row, but I know NO coding at all and my current script is compiled from things I've found around the web and the reference material.
Any advice would be greatly appreciated.
function onEdit(e) {
var spreadsheet = SpreadsheetApp.openById("sheetid");
var sheet = spreadsheet.getSheets()[0];
var lastrow = sheet.getLastRow();
var range = sheet.getRange(2,2,1,7);
values = range.getValues();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var SSsheet = ss.getSheets()[1];
var ssRange = SSsheet.getRange(2,3,1,7);
ssRange.setValues(values);
}
Try using copyTo(destination). It copies the data from a range of cells to another range of cells. Both the values and formatting are copied.
// The code below will copy the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
}
You can also try using copyValuesToRangecopyValuesToRange.
For additional code samples, you may also refer to this forum.
function onEdit(e) {
var spreadsheet = SpreadsheetApp.openById("ID");
var sheet = spreadsheet.getSheets()[0];
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A"+(lastRow)+":G"+(lastRow));
var values = range.getValues();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var SSsheet = ss.getSheets()[1];
var getRow = SSsheet.getLastRow() + 1;
var ssRange = SSsheet.getRange(getRow, 1, values.length, values[0].length);
ssRange.setValues(values);
Try with this,
this code copies the last value you want from a certain range and pastes it in the last available row of the other sheet.
The code it's the same only in the place where you are going to copy it, specify it to be the size of what I want to copy. I hope it helps you :D
I'm trying to use HTTP Get in Google Spreadsheet, to be able to create a URL to a specific cell in a sheet. I've been searching for how to do it, and I've tried using this way (the GET part), for example.
Here's the code I've put together:
function doGet(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Kunder");
var row = e.parameter["row"];
var col = e.parameter["col"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(row, col);
SpreadsheetApp.setActiveSheet(sheet);
SpreadsheetApp.setActiveRange(range);
}
And this is an example URL:
https://docs.google.com/spreadsheets/d/[spreadsheet ID]/edit?row=5&col=1
When I run the script I get this error:
TypeError: Cannot read property "parameter" from undefined.
I'm I doing something wrong? Or isn't it possible?
Thanks in advance,Oskar
EDIT
This is my current code:
function doGet(e){
var ss = SpreadsheetApp.openById("[id]");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = ss.getSheetByName("Kunder");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
SpreadsheetApp.setActiveSheet(sheet);
SpreadsheetApp.setActiveRange(range);
}
The code runs but finishes with
The script completed but did not return anything.
I want to open the spreadsheet and then set the active range from the GET parameters.
The url you show is not valid.
To use that kind of script you have to deploy the script as a webapp and use the resulting .exec url with parameters.
At the end it will look like this :
https://script.google.com/macros/s/AKfycbygwUwXXXXXXXXxJcKpBvsbflmnZ0Uqfu-JISWTZNvar32s3v_hl/exec?row=5&col=1
EDIT : there will be no activeSheet in that context, use openById or openByUrl instead.
Also the values you get for row and columns are strings, you should make them integers and use a normal sheet.getRange(row,col) to select a range.
EDIT2 :
this url :
https://script.google.com/macros/s/AKfycbwZbGW6E483BUplvLjCjNCXKjjiRorqzR9lruSydogeuU-YIvID/exec?row=1&col=1
and this code :
function doGet(e){
var ss = SpreadsheetApp.openById("1sbJXuEpL_88-u-Bm4QOCAM3SVddFwZKI0c1kxeRpcos");
var sheet = ss.getSheetByName("Sheet1");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
sheet.getRange(row, col).setValue('test ok')
}
writes in this sheet : see cell A1 or test on another row and column.
You'll indeed receive a message that nothing was returned and this is actually true ! we don't return anything in that code, this is just a demo ;-)
EDIT 3 : as mentioned in the comments, to get something returned by this function you have to resturn something...
Here is an example :
function doGet(e){
var ss = SpreadsheetApp.openById("1sbJXuEpL_88-u-Bm4QOCAM3SVddFwZKI0c1kxeRpcos");
var sheet = ss.getSheetByName("Sheet1");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
var value = sheet.getRange(row, col).getValue();
sheet.getRange(row, col).setValue('test ok');
var stringValue = value==''?'empty':value;
Logger.log(stringValue);
return ContentService.createTextOutput(stringValue).setMimeType(ContentService.MimeType.TEXT);
}