Cannot find method getRange(number,number,number,number) - javascript

In an attempt to stream line some processes I have attempted to create a script to move a paper process into a google form. I've nhever really tinkered with Javascript but I have been following the trail of errors down to this one which I cannot seem to shake.
Currently I'm trying to define the range of data but keep getting the error mentioned in the title. Am I incorrectly calling the sheet in the script? I cannot seem to figure out how to properly define them.
Below is the section that defines the variables and sheets. Anything I'm doing incorrectly?
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
Logger.log(ss.getName());
var sheet = ss.getActiveSheet()[0];
var startRow = 2;
// First row of data to process
var numRows = 12;
// Number of rows to process
var dataRange = ss.getRange(startRow, 2, numRows, 12)
//Assigning spreadsheet feilds
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var firstName = row[1];
var guestFirstN = row[6];
var guestLastN = row[7];
var arrivalDate = row[8];
var numberNights = row[9];
var rmName = row[10];
var rmAgree = row[11];

You first need to define the Sheet you want to get the data from since a Spreadsheet can have multiple Sheets.
Try replacing
var dataRange = ss.getRange(startRow, 2, numRows, 12)
with
var dataRange = ss.getActiveSheet().getRange(startRow, 2, numRows, 12);

Related

Getting error when set values ​into getRange() - Google Apps Script

Objective
Get the rows where the dates in column A are within the range of this current month and year. In the rows that coincide in month and year with the current date, the value "yes" will be placed in the cell of column O (col. 15 - Array 14). The non-matching rows will be placed the value "no" in the cell of column 0 (col.15). Finally, checkboxes will be created for the entire column O (col.15), and depending on the value of the cell, the checkboxes will be marked or not.
Problem
I am getting an error "Exception: Service error: Spreadsheets" in the line of code dataRange.setValues(dataValues); And I don't know why or how to fix it.
This error in GAS is not explained any more. I have looked for solutions online but despite following the instructions, I can not solve this.
My code
function thisMonth() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('πŸ“… Todos los eventos');
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
var dataRange = sheet.getRange(2, 1, lastRow -1, lastCol);
var dataValues = dataRange.getValues();
const now = new Date();
const month = now.getMonth();
const year = now.getFullYear();
dataValues.forEach((fila)=> {
var dateColA = new Date(fila[0]);
if ( month == dateColA.getMonth() && year == dateColA.getFullYear() ){
fila[14] = 'yes';
Logger.log(dateColA + ' - ' + fila[3]);
} else {
fila[14] = 'no';
}
})
dataRange.setValues(dataValues);
sheet.getRange(2, 15, lastRow -1, 1).insertCheckboxes('yes');
}
I tested your code and it works with a small sample sheet I made. Not sure about your exact error but I've heard it could be related to reaching some kind of limit when handling Sheet data. With that in mind, you should try to optimize it. You don't need to get the entire x-rows by 15-columns range and manipulate it then completely rewrite it to the Sheet, when all you want is to edit the "O" column.
I suggest you instead try to optimize your code to only get the values from column "A" to compare the dates, then create a local array to build the "O" column and then set the values to just that column. Here's a sample that worked for me:
function thisMonth() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('πŸ“… Todos los eventos');
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
var dataRange = sheet.getRange(2, 1, lastRow -1);
var checkboxRange = sheet.getRange(2, 15, lastRow -1)
var dataValues = dataRange.getValues();
var checkboxValues = []
const now = new Date();
const month = now.getMonth();
const year = now.getFullYear();
for (i = 0; i<dataValues.length; i++){
if (dataValues[i][0].getMonth()==month && dataValues[i][0].getFullYear()==year){
checkboxValues.push(["yes"])
}else{
checkboxValues.push(["no"])
}
}
checkboxRange.setValues(checkboxValues);
sheet.getRange(2, 15, lastRow -1).insertCheckboxes('yes');
}

drive.properties for loop with google sheets

I have two functions in a google sheet that are meant to loop through a single column containing the file IDs of files in google drive, issuing a Properties.get to retrieve a single property "LastReview" for each document and paste all of the LastReview times in the next available column.
I'm having trouble getting the loop in "loopForMetadata" to work. I want it to acquire a list of all the LastReview times associated with each fileID and then post that to the next available column so that all of the LastReview times align with the fileIDs.
function getProperty(fileId) {
var propertyKey = 'LastReview'
var fileId = '1UaQkJU8r1kE9sxpFg6OD8aOuUCoRnSpB9Agg_R9HJ3s'
var response = JSON.stringify(Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value);
var key = "value";
var resposeNoQuote = response.replace(/\"/g, "")
Logger.log(resposeNoQuote);
}
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
// Get array of values in the search Range
var rangeValues = searchRange.getValues();
// Loop through array and if condition met, add relevant
// background color.
var resultValues = []
for (i = 0; i < rangeValues.length; i++) {
resultValues.push(getProperty(rangeValues[i]));
Utilities.sleep(10);
}
Logger.log(resultValues);
};
I believe your goal as situation as follows.
You want to retrieve the values using the key of LastReview in the property from the files of fileId.
You want to put the retrieved values to the same row of fileId in the next available column.
You want to achieve this using Google Apps Script.
Modification point:
In your script,
getProperty() doesn't return the values.
resultValues is not put to the Spreadsheet.
When you want to retrieve the value of the key LastReview, Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value directly returns the value.
As an important point, when the file of fileId has not property of the key LastReview, it seems that Drive.Properties.get() occurs an error. So in this modification, as a simple workaround, I used the try catch.
When above points are reflected to your script, it becomes as follows.
Sample script:
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
var rangeValues = searchRange.getValues();
var resultValues = []
// I modified below script.
for (i = 0; i < rangeValues.length; i++) {
var fileId = rangeValues[i];
var value = "";
try {
value = Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value;
} catch(e) {}
resultValues.push([value]);
// Utilities.sleep(10); // I'm not sure whether this is required.
}
sheet.getRange(2, lastColumn + 1, resultValues.length, 1).setValues(resultValues);
Logger.log(resultValues);
};
Note:
Please confirm whether Drive API is enabled at Advanced Google services, again.
Reference:
Properties: get

Script got caught in loop for 3-5 times and then stop

I am working on App script for my project. I am very new at all programming languages. I have been having the problem with a specific section of code that it run in loop for 3-5 times then stop by itself. The whole code is
var EMAIL_SENT = "EMAIL_SENT";
function Test() {
autofill();
replace();
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var lastColumn = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var lastRow = sheet.getLastRow();
var service = sheet.getRange(lastRow, 11).getValue();
if (service === 0) {
filterBTC();
codeBTC();
} else {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('K1').activate();
var criteria = SpreadsheetApp.newFilterCriteria()
.setHiddenValues(['0'])
.build();
spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(11, criteria);
spreadsheet.getRange('B1').activate();
spreadsheet.getActiveSheet().getFilter().sort(2, true);
spreadsheet.getRange('B3').activate();
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('B3:B561'),
SpreadsheetApp.AutoFillSeries.ALTERNATE_SERIES);
spreadsheet.getRange('B3:B561').activate();
SendOrder();
removefilters();
}
}
}
The section that got stuck in loop is
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('K1').activate();
var criteria = SpreadsheetApp.newFilterCriteria()
.setHiddenValues(['0'])
.build();
spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(11, criteria);
spreadsheet.getRange('B1').activate();
spreadsheet.getActiveSheet().getFilter().sort(2, true);
spreadsheet.getRange('B3').activate();
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('B3:B561'),
SpreadsheetApp.AutoFillSeries.ALTERNATE_SERIES);
spreadsheet.getRange('B3:B561').activate();
SendOrder();
removefilters();
Please help, I've been trying to finish this project for almost a week now.
Thank you!
If you are very new programmer first things you should learn is how to debug your code and run script by steps and see how every variable/object changing instead of making thousands of Logs

Reading a cell value using java or google script

I need a help reading cell value using either java or google script. The cell I am trying to read has a formula. When my script reads the data I get #DIV\0! error.
here is my simple script:
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getDataRange();
Data = Range.getValues();
WR = Data[30][15];
}
Any help will be appriciated, Thanks.
Instead of doing [30][15], use this code to limit the range to one cell.
If that doesn't work, maybe your cell actually contains this DIV/0 value?
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getRange(30, 15); //changed here
Data = Range.getValue(); //and here
WR = Data; //and here
}

Trouble with a simple GoogleScript code (google sheets + gmail integration)

function checkReminder() {
// get the spreadsheet object
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// set the first sheet as active
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
// fetch this sheet
var sheet = spreadsheet.getActiveSheet();
// figure out what the last row is
var lastRow = sheet.getLastRow();
// the rows are indexed starting at 1, and the first row
// is the headers, so start with row 2
var startRow = 2;
// grab column 10 (the 'date end' column)
var range = sheet.getRange(2,10,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var date_end_values = range.getValues();
// Now, grab the Event name data
range = sheet.getRange(2, 5, lastRow-startRow+1, 1);
var reminder_info_values = range.getValues();
var warning_count = 0;
var msg = "Send out a follow-up email asking how the event was!";
}
//Get today's date
var todaysDate = new Date();
var numRows = numRows
// Loop over the days left values
for (var i = 0; i <= numRows - 1; i++) {
var date_end = date_end_values[i][0];
//call setHours to take the time out of the comparison
if(date_end == todaysDate.setHours(0,0,0,0)) {
MailApp.sendEmail("max#xpogo.com",
"Reminder Spreadsheet Message", msg);
}
What I'm trying to do is have gmail send me a reminder when a certain column in my data set is equal to the present date. Im new to coding and am running into trouble. Please help?
I added the following after your variables were set, to determine whether they were commensurate for your comparison (hit ctrl+Enter after executing to view the log).
Logger.log(date_end);
Logger.log(todaysDate.setHours(0,0,0,0));
They weren't comparable at all. Here are the lines I changed to make this work:
var todaysDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
var date_end = Utilities.formatDate(date_end_values[i][0], "GMT+1", "MM/dd/yyyy");
if(date_end == todaysDate) {
HTH

Categories