Google Apps Script "cannot find function" offset in object - javascript

Can any help with the following issue??? Pretty new to app script / javascript and would appreciate any help or guidance to figure out..
TypeError: Cannot find function offset in object Timestamp, (then continues listing the column headings in the red warning banner.
function uiSendLogEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
data = data.offset(1,0,data.getNumRows())-1;
// For Loop
for ( var i = 0; i < data.length; i++ ) {
var row = data[i];
var approved = row[5];
var sentEmail = row[6];
var snapshot = row[3];
//if stmt in For Loop
if ( approved != "Yes" ) {
data[i][5] = "Yes";
data.getDataRange().setValues(data);
}// if stmt end curly
else if ( approved == "Yes" && sentEmail != "Yes" ) {
data[i][6] = "Yes";
data.getDataRange().setValues(data);
GmailApp.sendEmail("email#email.com", "subject", "body" + "whatever " + snapshot);
}//else if end curly
else {
return;
}//else stmt end curly
}// for loop end curly
}

I made a few basic tweaks that will hopefully point you in the right direction (and thanks to #AdamL for the .shift() method - much better than what I had in there before :) ):
function uiSendLogEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
// Move the values down
data.shift();
// For Loop
for ( var i = 0; i < data.length; i++ ) {
var row = data[i];
var approved = row[5];
var sentEmail = row[6];
var snapshot = row[3];
// Here we set a range equal to the data range offset by 1 + our current
// position in the loop (cycling through rows), and then get the A1 notation
// of the first row, which we use to get that particular range and prep
// it for adding values
var rng = sheet.getDataRange().offset(i+1,0,1).getA1Notation();
myRange = sheet.getRange(rng);
//if stmt in For Loop
if ( approved != "Yes" ) {
// Here we can just work with the row element itself
row[5] = "Yes";
// Because setValues expects a two dimensional array,
// we wrap our row in brackets to effectively convert it to one
myRange.setValues([row]);
} // if stmt end curly
else if ( approved == "Yes" && sentEmail != "Yes" ) {
// Same here as above
row[6] = "Yes";
myRange.setValues([row]);
GmailApp.sendEmail("email#email.com", "subject", "body" + "whatever " + snapshot);
}
else {
return;
}
}

I think you are wanting to remove the first row of data (the headers); so if that's the case, try replacing:
data = data.offset(1,0,data.getNumRows())-1;
with
data.shift();

Related

Method search on google sheet data from one column using google script?

I had tried to search data like below flow picture and script to search data from google sheet using google app script but the script using is not working properly but can someone tell me how to setup search function to find data like flow on image? thanx
[Flow searching data][1]
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Search", functionName: "searchRecord"} ];
ss.addMenu("Commands", menuEntries);
}
function searchRecord()
{
var ss = SpreadsheetApp.getActiveSpreadsheet()
var wsSearchingData = ss.getSheetByName("Searching Data")
var wsDatabase = ss.getSheetByName("Database")
var searchString = wsSearchingData.getRange("E4").getValue();
var column =1; //column Index
var columnValues = wsDatabase.getRange(2, column, wsDatabase.getLastRow()).getValues(); //1st is header row
var searchResult = columnValues.findIndex(searchString); //Row Index - 2
var searchValue = wsDatabase.getRange("B2:B2041").getValues()
var matchingDatabase = searchValue.map(searchColumn => {
var matchColumn = columnValues.find(r => r[0] == searchColumn[0])
return matchColumn = matchColumn ? [matchColumn[2]] : null
})
console.log(matchingDatabase)
if(searchResult != -1)
{
//searchResult + 2 is row index.
SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 1, 1))
}
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
wsSearchingData.getRange("B11").setValue(search[0]);
wsSearchingData.getRange("C11").setValue(search[1]);
wsSearchingData.getRange("D11").setValue(search[2]);
wsSearchingData.getRange("E11").setValue(search[3]);
wsSearchingData.getRange("F11").setValue(search[4]);
return;
}
}
[1]: https://i.stack.imgur.com/HF9K8.png
var searchResult = columnValues.findIndex(searchString); //Row Index - 2
replace the above code with:
var searchResult = columnValues.filter(r=>r[1]==searchString)
You can then put searchResult directly as output in the sheet. Make sure that [1] in the above contains the column index of Name in the columnValues Array.

GAS Function not setting value as intended in sheet

This is the Google Sheet, it can be copied: https://docs.google.com/spreadsheets/d/1ffIRGiGkiy5WFzSAvWNOY_3cqNXgTAOtO6o8vxS-BFU/edit?usp=sharing
The Function 'AddNewMembers' does not function, even if "isAdded == "No" it will not setValue(recruit_id)
function AddNewMembers(event){
event = {range: SpreadsheetApp.getActiveRange()}
CheckHandleSteamIDNotation(event)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var recruitment_log = ss.getSheetByName('RL1');
var main_roster = ss.getSheetByName('Main Roster');
var isAdded = recruitment_log.getRange('R3').getValue();
if(isAdded == "No") {
var recruit_id = "'" + recruitment_log.getRange('J3').getValue();
main_roster.getRange('I100').setValue(recruit_id);
}
}
function CheckHandleSteamIDNotation(event)
{
let formSheet = SpreadsheetApp.getActiveSheet();
let header = formSheet.getRange(1,1,1,formSheet.getMaxColumns()).getValues();
let formRange = formSheet.getRange(formSheet.getLastRow(), 1, 1, formSheet.getMaxColumns());
let formValues = formRange.getValues();
for(let i = 0; i < header[0].length; i++)
{
if(header[0][i].includes("SteamID"))
{
formValues[0][i] = "'" + formValues[0][i];
}
}
formRange.setValues(formValues);
}
Since the provided script above contains var isAdded = recruitment_log.getRange('R3').getValue(); the value of R3 is currently set to "Yes" that is why the condition for the script below is not running.
if(isAdded == "No") {
var recruit_id = "'" + recruitment_log.getRange('J3').getValue();
main_roster.getRange('I100').setValue(recruit_id);
}
Try this modification:
function AddNewMembers(event) {
event = { range: SpreadsheetApp.getActiveRange() }
CheckHandleSteamIDNotation(event)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var recruitment_log = ss.getSheetByName('RL1');
var main_roster = ss.getSheetByName('Main Roster');
//Gets all the data values on recruitment_log
var isAdded = recruitment_log.getRange(3, 1, recruitment_log.getLastRow(), recruitment_log.getLastColumn()).getValues();
//Gets the last row starting I17
var lastrow = main_roster.getRange(17, 9, main_roster.getLastRow() , 1).getValues().filter((x => x > 1)).length
//Sets the value on the last blank row
isAdded.map(x => x[17].toString().toLocaleLowerCase() == "no" ? "'" + main_roster.getRange(17 + lastrow,9).setValue(x[9]) : x)
}
I made modifications on your isAdded variable to the following to get the entire range of data on RL1 sheet.
var isAdded = recruitment_log.getRange(3, 1, recruitment_log.getLastRow(), recruitment_log.getLastColumn()).getValues();
This part of script was only used to get the current length of data for the New Operatives. Using .filter() method to filter out empty array elements, since getValues() gets blank cells if there is formatting applied on the spreadsheet.
var lastrow = main_roster.getRange(17, 9, main_roster.getLastRow() , 1).getValues().filter((x => x > 1)).length
Using ES6 .map() method to create a new array for the data that hasn't been added to the main roster sheet file.
isAdded.map(x => x[17].toString().toLocaleLowerCase() == "no" ? "'" + main_roster.getRange(17 + lastrow,9).setValue(x[9]) : x)
Screenshot:
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#description

How to send full row and list name from Google Sheet, not only specific (fixed) cells and list name?

So I have a script, that sends msg to group chat, if in Column ( 2 ) in any cell's some one printed "Yanson" bot sends only fixed cell - .getRange(row,8). In my case this cell holds link to document.
Bot msg looks like this - Link to document New Added Document List Name ( This time I get List name coz it fixed in var ws, if script work's in another list , I don't receive the right list Name I still receive the fixed one in var ws)
If we delete === ws and print "Yanson" in another list - I'll receive only info from .getRange(row,8) and "Added New Document.
But I need to send full string ( row ) with all the cell inside it, not only cell 8 with link. And I also need to see in msg from bot list name where "Yanson" was printed. Because I have more then 10+ list in Sheet. Sheet looks like this Tablepicture
const token = "Token";
function onEdit(e) {
sendTelegram(e)
}
function sendTelegram(e){
var row = e.range.getRow();
var col = e.range.getColumn();
var startRow = 2; // Starting row
var targetColumn = 2; // If in this column, cell changes to Yanson - send to Telegram
var ws = "List name"; //List name
let chatId = "ChatId";
let Company = e.source.getActiveSheet().getRange(row,8).getValue();
var text = encodeURIComponent(Company + " New Document Added" + ws)
var currentDate = new Date();
var url = "https://api.telegram.org/bot" + token + "/sendMessage?chat_id=" + chatId + "&text=" + text;
if (col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
if(e.source.getActiveSheet().getRange(row,2).getValue() == "Yanson"){ //Yanson - Trigger. If Yanson printed in cell in column 2 - send to telegram
sendText(chatId,Company + " New Document Added" +" "+ ws);
//Doing nothig right now.
// e.source.getActiveSheet().getRange(row,4).setValue(currentDate);
// if(e.source.getActiveSheet().getRange(row,3).getValue() == ""){
// e.source.getActiveSheet().getRange(row,3).setValue(currentDate)
// }
}
}
}
Based on what I could gather from your description, you are looking for a way to send the entire contents of the row as a string.
To do that, you get the range of that row, which looks like this:
sheet.getRange(starting row, starting column, # of rows, # of cols)
Sheets uses a two dimensional array that looks like this:
[[row1Col1, row1Col2, row1Col3], [row2Col1, row2Col2, row2Col3], etc]
const token = "Token";
function onEdit(e) {
sendTelegram(e)
}
function sendTelegram(e){
var row = e.range.getRow();
var col = e.range.getColumn();
var startRow = 2; // Starting row
var targetColumn = 2; // If in this column, cell changes to Yanson - send to Telegram
var ws = "List name"; //List name
/*--- Updated this section ----*/
//Adding variables to improve readiblity
var sheet = e.source.getActiveSheet();
var sheetName = e.source.getActiveSheet().getName();
let company = e.source.getActiveSheet().getRange(row,8).getValue();
var listName = ; //Is the list name the same as the sheet name? if not, reference the list names location here
//Define the range of the whole row
var firstCol = 1;
var numOfCols = 8;
var fullRowValues = sheet.getRange(row, firstCol, 1, numOfCols).getValues();
//since this is a single row, you can use .flat() to make it a 1D array
//Then convert it to a string
var fullRowString = fullRowValues.flat().toString();
/*---- End updates ---*/
let chatId = "ChatId";
var text = encodeURIComponent(Company + " New Document Added" + ws)
var currentDate = new Date();
var url = "https://api.telegram.org/bot" + token + "/sendMessage?chat_id=" + chatId + "&text=" + text;
if (col === targetColumn && row >= startRow && sheetName === ws){
if(company == "Yanson"){ //Yanson - Trigger. If Yanson printed in cell in column 2 - send to telegram
// Not sure what the output is supposed to look like,
// so I just added it to the end of your existing output
sendText(chatId,Company + " New Document Added" +" "+ ws + " All Values: " + fullRowString);
//Doing nothig right now.
// e.source.getActiveSheet().getRange(row,4).setValue(currentDate);
// if(e.source.getActiveSheet().getRange(row,3).getValue() == ""){
// e.source.getActiveSheet().getRange(row,3).setValue(currentDate)
// }
}
}
}
function onEdit(e) {
const sh = e.range.getSheet();
const row = sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getDisplayValues()[0].join(',');//current row of active sheet
const name = e.source.getName();//spreadsheet name
//const name = sh.getName();//sheet name not sure which one you want
sendText('chatId', `${name)\n ${row}`);
}
You probably want to limit the trigger to a certain sheet and given row and column but I'll leave that up to you.

Google Sheets Script Missing Something

I'm creating a small database inside a sheet, I need the script to copy data to another sheet tab and I'm getting an empty error.
I'm not expert on javascript so what code I'm missing here?
Basically, when you press a button you get a text modal with an input so the person writes the name and then the script gets all the Rows with a TRUE (checkbox) and copies everything to another sheet with a header saying the data and time with the name of the person. If returns nulled with everything FALSE wont copy and shows a text modal saying that there's no task done today.
Thanks in advance
function moveValuesOnly() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getRange ("RESUMO!A4:J99");
var destSheet = ss.getSheetByName("LOG Resumo");
var row = destSheet.getLastRow()+2; //the starting column of the range
var column = 1; //the starting row of the range
var numRows = 97; //the number of rows to return
var numColumns = 10; //the number of columns to return
var destRange = destSheet.getRange(row, column, numRows, numColumns);
var input_text = Browser.inputBox("Encarregado de Turno","Escreve seu nome:", Browser.Buttons.OK);
var now = new Date();
var active = ss.getSheetByName("RESUMO");
var condition = active.getRange('RESUMO!J4:J99').getValue();
var valueToWatch = "TRUE";
if (condition == valueToWatch) {
destSheet.getRange(row-1,1,1,10).mergeAcross().setBackgroundRGB(224, 102, 102).setFontColor("white");
destSheet.getRange(row-1,1,1).setValue(now + " ~~ ENCARREGADO DE FECHAR TURNO: " + input_text).activate();
source.copyTo(destRange, {contentsOnly: true}).setFontColor("black");
} else {
Browser.msgBox("Erro","Não exite tarefas completas hoje", Browser.Buttons.OK);
}
}
There are following issue with your code:
If you have TRUE and FALSE values as cell contents, Spreadsheets will automatically identify them as booleans, rather than strings. Thus, also valueToWatch needs to be a boolean rather than a string: var valueToWatch = true;
If you want to verify the "TRUE" condition for each row - you need to do it in a loop. Consequently, you code needs to be modified a bit. One way to do so is to push all rows where the cell content in column J is TRUE into an array and then pass the contents of this array to a destination range with the same dimension as the array. This is what the resulting code would look like:
function moveValuesOnly() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getRange ("RESUMO!A4:J99");
var destSheet = ss.getSheetByName("LOG Resumo");
var row = destSheet.getLastRow()+2; //the starting column of the range
var column = 1; //the starting row of the range
var input_text = Browser.inputBox("Encarregado de Turno","Escreve seu nome:", Browser.Buttons.OK);
var now = new Date();
var active = ss.getSheetByName("RESUMO");
var condition = active.getRange('RESUMO!J4:J99').getValues();
destSheet.getRange(row-1,1,1,10).mergeAcross().setBackgroundRGB(224, 102, 102).setFontColor("white");
destSheet.getRange(row-1,1,1).setValue(now + " ~~ ENCARREGADO DE FECHAR TURNO: " + input_text).activate();
var valueToWatch = true;
var values=source.getValues();
var array=[];
for(var i=0;i<condition.length;i++){
if (condition[i][0] == valueToWatch) {
array.push( values[i]);
}
}
if(!array) {
Browser.msgBox("Erro","Não exite tarefas completas hoje", Browser.Buttons.OK);
}
else {
var numRows = array.length; //the number of rows to return
var numColumns = array[0].length; //the number of columns to return
var destRange = destSheet.getRange(row, column,numRows , numColumns);
destRange.setValues(array).setFontColor("black");
}
}

"The coordinates of the target range are outside the dimensions of the sheet" error when looping [duplicate]

This question already has an answer here:
Copying data script is not working anymore
(1 answer)
Closed last month.
I have 4 sheets. Form, Raw, URL and USA/Japan/Canada. I get the spreadsheet url value from the URL sheet and use 'IMPORTRANGE' in the Raw sheet to transfer the data table. From there, i loop through the table in Raw sheet to check if the values is match from the values in the Form sheet. If it's matched, i will transfer that row in the USA/Japan/Canada sheet.
So i got this code in my google sheets:
var mainWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form');
var continentWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('USA/Japan/Canada');
var rawWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Raw');
var urlWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('URLs');
var tourName = mainWS.getRange('C4').getValue();
var depDate = new Date(mainWS.getRange('C5').getValue());
var status = mainWS.getRange('C6').getValue();
//extract table data
var url = urlWS.getRange("B4").getValue();
rawWS.getRange('A1').setValue('=IMPORTRANGE("' + url + '","Main Data!A1:AE")');
var dummyHolder = rawWS.getRange("B1:B").getValues();
var lastRow = dummyHolder.filter(String).length;
Logger.log(lastRow);
//loop through the raw extract
for(var i = 2; i <= lastRow; i++){
var dateHolder = new Date(rawWS.getRange("E" + i).getValue());
if(rawWS.getRange("F" + i).getValue() == tourName && rawWS.getRange("I" + i).getValue() == status && dateHolder.getTime() === depDate.getTime()){
var continentLR = continentWS.getLastRow() + 1;
rawWS.getRange('Raw!' + i + ':' + i + '').copyTo(continentWS.getRange(continentLR, 1), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
}
Then i suddenly get the "The coordinates of the target range are outside the dimensions of the sheet" error message once it enters the loop. Specifically in the first line after the for loop:
var dateHolder = new Date(rawWS.getRange("E" + i).getValue());
To be clear, the rawWS where it is looping has 134 records and it registers 134 as its last row. I don't know why i am getting an error here.
When i remove that line, it still gives me an error on the next line. It all errors inside the for loop.
Any ideas?
I haven't tested this but give it a try:
I think that the problem with filter is that it will remove blanks before the end as well but getValues() won't. So you can end up with the wrong length depending upon the dataset.
function unknown() {
var formWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form');
var continentWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('USA/Japan/Canada');
var rawWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Raw');
var urlWS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('URLs');
var tourName = formWS.getRange('C4').getValue();
var depDate = new Date(formWS.getRange('C5').getValue());
var status = formWS.getRange('C6').getValue();
//extract table data
var url = urlWS.getRange("B4").getValue();
rawWS.getRange('A1').setValue('=IMPORTRANGE("' + url + '","Main Data!A1:AE")');
var dummyHolder = rawWS.getRange(1,2,rawWS.getLastRow(),1).getValues();
for(var i=dummyHolder.length-1;i>=0;i--){
if(!dummyHolder[i][0]){
dummyHolder.splice(i,1);
}else{
break;
}
}
//loop through the raw extract
for(var i=2;i<dummyHolder.length; i++){
var dateHolder = new Date(rawWS.getRange(i,5).getValue());
if(rawWS.getRange(i,6).getValue() == tourName && rawWS.getRange(i,9).getValue() == status && dateHolder.getTime() === depDate.getTime()){
var continentLR = continentWS.getLastRow() + 1;
rawWS.getRange(i,1,).copyTo(continentWS.getRange(continentLR, 1), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
}
}
Array Filter Method
Also your last line included sheet name in the range but rawWS is that sheet. So I rewrote the range parameters. Sorry if this doesn't work.

Categories