Google Appscript Error Exception issue with recordset [duplicate] - google-apps-script

This question already has an answer here:
Cannot find method getRange(number,number)?
(1 answer)
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
To be clear, I looked at other posts in Stackoverflow on this issue before posting the problem. So far nothing has helped so i am reaching out to the community to help. The error is:
Error Exception: The parameters () don't match the method signature
for SpreadsheetApp.Spreadsheet.getRange.
Here is what i have in a function called code.gs
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var ss = spreadsheet.getSheetByName("Main");
var configSheet = spreadsheet.getSheetByName("Config");
function createid()
{
var colnum = getColIndexByNameandRow("UID",ss,1)
};
UID is an actual row header in my spreadsheet, and I want to return the column number from the sheet. I developed a function that returns the column Index. The function is listed below
function getColIndexByNameandRow(colName,mysheet,rs)
{
/*
ColName is the name of the column your looking for, string value
mysheet is the recordset for the sheet you are searching for the column
(R)ow (S)tart (rs) is the row position where you want the column search to start
*/
if (rs==undefined) rs=1;
var numColumns = mysheet.getLastColumn();
var row = mysheet.getRange(rs, 1, 1, numColumns).getValues();
for (i in row[0]) {
var name = row[0][i];
if (name == colName)
{
return parseInt(i) + 1;
}
}
return -1;
};
I know my ss active sheet declaration is working because the line before it var numColumns = mysheet.getLastColumn(); works fine and returns the number of rows. The following line chokes every time it runs:
var row = mysheet.getRange(rs, 1, 1, numColumns).getValues();
Whats interesting is I am using the same function with another project, and its flawless n no issues.
I have tried changing .getValues() to .getDisplayValues() with no success.
Anyone got anything else I can try.
Thanks in advance!

I was able to resolve this problem. I renamed the ss SpreadsheetApp to the mainsheet, and it worked. I am not sure why that is, but it doesn't seem to like the use of ss as a SpreadsheetApp. I added my sample test that worked
function test(){
var val = getColIndexByNameandRow("UID",mainsheet,1)
Logger.log(val)
}

Related

Script - Add/Remove Google Sheet Editors for a list

Example Document: Link
I have had a working script that would add or remove editors from a specified sheet ID for a good few months until recently it has started giving an error of:
Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Spreadsheet.removeEditor.
Nothing has changed recently regarding the input I am providing the script so I am at a bit of a loss.
The script is as follows:
function runEmailAccess(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sEditors = ss.getSheetByName('Editors');
var sheet = SpreadsheetApp.openById("SHEETID");
var nAddEditor = sEditors.getRange('A2').getValue();
if (nAddEditor != 0){
var vAddEditor = sEditors.getRange('A3:A'+nAddEditor).getValues();
sheet.addEditors(vAddEditor);
}
var nRemoveEditor = sEditors.getRange('B2').getValue();
if (nRemoveEditor != 0){
var vRemoveEditor = sEditors.getRange('B3:B'+nRemoveEditor).getValues();
for (j=0;j<vRemoveEditor.length;j++) {
sheet.removeEditor(vRemoveEditor[j])
}
}
}
The script takes the row number of last email in the list from Row 2 then takes the emails for row 3 to that row via .getRange.
Any help regarding this would be of great help.
Thanks.
vRemoveEditor is 2D array. You're indexing only into the outer array with vRemoveEditor[j]. You need to index into both to get primitive values: vRemoveEditor[j][0]

Error only appears when running script in Apps Script Editor

I am trying to run a script that auto-populates the date in column F whenever data is entered or changed in column E in a spreadsheet with multiple sheets.
I currently have a script which was written for me based on what I described but I was getting an error code. I went back to my original question and explained that this script was needed to run on a single sheet within a spreadsheet with multiple sheets. He gave me some additional information but this was his last answer "yes, you will need to replace event.source.getActiveSheet() with something like "getsheetbyname". I have tried everything that is within my limited knowledge to work with what he gave me but I am still getting an error code no matter what I try.
Here is the area that is giving me the error.
var sheet = event.source.getsheetbyname();
Here is the error code I am receiving
TypeError: Cannot read property "source" from undefined. (line 2, file "Code")
I am aware that there needs to be the name of the sheet I am wanting the script to run on but I do not know how to code it to do so. The name of the sheet is "Juvenile weights"
The expected results should be when I add or change the data in column E it should auto-populate the current date into the adjacent cell in the adjacent column.
When I save the script and then run the script to make sure it's working, of course, it gives me the error code I described above. Then when I go back to that sheet after saving the script instead of auto-populating the date, now when I highlight a string of cells in a row it changes all the following cells to the same information I have in the first cell I started highlighting. Very odd!
The script + error code:
The code:
function onEdit(event) {
var sheet = event.source.getActiveSheet();
// note: actRng = the cell being updated
var actRng = event.source.getActiveRange();
var index = actRng.getRowIndex();
var cindex = actRng.getColumnIndex();
if (cindex == 5) { // 1 == Column A, 2 == Column B, 3 == Column C, etc.
var dateCol = sheet.getLastColumn();
var lastCell = sheet.getRange(index,dateCol);
var date = Utilities.formatDate(new Date(), "EST", "MMM-dd-yyyy");
lastCell.setValue("'" + date);
}
}
I believe this does the same thing:
function onEdit(e) {
var sheet = e.range.getSheet();
if (e.range.columnStart == 5) {
sheet.getRange(e.range.rowStart,sheet.getLastColumn()).setValue("'" + Utilities.formatDate(new Date(), "EST", "MMM-dd-yyyy HH:mm:ss"));
}
}
Is there a reason you aren't using SpreadsheetApp.getActiveSheet().getSheetByName("Juvenile weights");

Convert from A1 notation to a string/list notation?

I'm attempting to write a script to protect all of a sheet from edits, except for a couple of sections. I currently get the error "Cannot convert Array to Range[]."
I am currently under the impression that I need to write it in a string notation (I thinks that's what it's called) such as (4,3,3,2) for ['C4:D7'] in the format (firstRow, firstColumn, Number of Rows, Number of Columns) as I currently understand it.
this is the script currently:
function Protect() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var protection = spreadsheet.protect();
protection.setUnprotectedRanges(['C4:D7', 'C11:D13', 'C18:E20', 'F18:G18', 'C23:G25', 'C30:D32'])
};
So my main question is what should my line 4 be because nothing I have tried works, (and if you use an example can I request that you use an actual example because i find that I really struggle to get what to do when people use placeholders in their answers)
and a sort of sub question is: Is there a way to convert from A1 to string notation (sort of a reverse)?
So just to be clear:
As Tanaike said:
function Protect() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var protection = spreadsheet.protect();
protection.setUnprotectedRanges(spreadsheet.getRangeList(['C4:D7', 'C11:D13', 'C18:E20', 'F18:G18', 'C23:G25', 'C30:D32']).getRanges());
}
And the Protect Ranges Dialog Confirms the Process worked:
A possible answer to sub question:
function convertA1ToList(A1string) {
var A1string=A1string || 'A1:Z100';//for debugging return for this is 1,1,100,26
if(A1string) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getRange(A1string);
var rowStart=rg.getRow();
var columnStart=rg.getColumn();
var numrows=rg.getHeight();
var numcols=rg.getWidth();
return Utilities.formatString('%s,%s,%s,%s',rowStart,columnStart,numrows,numcols);
}
}

onEdit installable trigger not firing when defining variable through array object

Hej!
I have a script that is supposed to be triggered onEdit.
onEdit() as a simple trigger is not an option for me, since the script needs authorizations. When setting an installable trigger with the editor the trigger is only fired when a specific variable is manually defined, but not when it is defined with an array.
Since I have no clue where the problem could be (I have tried to comment out the code part by part, but it always ends up not working when comming to the last part.
function myFunction() {
//Source Sheet for different sheets
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var activeRange = ss.getActiveRange();
var activeRow = activeRange.getRowIndex();
var CategoryValues = ss.getSheetValues(activeRow, 4, 1, 14);
var ID = activeSheet.getRange(activeRow,2).getValue();
var red = '#e06666'
// Defining the sourceWeekNumber in the sourceSheet with a while loop
var sourceWeeks = activeSheet.getRange(1,1,activeRow).getValues();
sourceWeeks.reverse();
var sourceWeekColor = activeSheet.getRange(1,1,activeRow).getBackgrounds();
sourceWeekColor.reverse();
var sourceWeekNumber = [];
var sourceWeekIndex=1;
while (sourceWeekColor[sourceWeekIndex-1]!=red) {
if (sourceWeekColor[sourceWeekIndex]==red) {
sourceWeekNumber.push(sourceWeeks[sourceWeekIndex])
}
sourceWeekIndex++;
}
//Target sheet is always mastersheet
var ts = SpreadsheetApp.openById('ID').getSheetByName('mastersheet');
//Finding the right spot in mastesheet
//Validate the weeknumber
var validWeek = ts.getRange(2, 1, ts.getLastRow()).getValues();
var rowIndex = [];
//-----> var sourceWeekNumber = 'v50'; <-----
// When defining this variable manually, onEdit works fine.
// When defining sourceWeek with the while loop above, the onEdit does not trigger.
// Find the right week and it's row in the mastersheet
var validWeekIndex = 1;
while (validWeek[validWeekIndex] != sourceWeekNumber) {
if (validWeek[validWeekIndex] == sourceWeekNumber) {
var validID = ts.getRange(validWeekIndex+3,2, ts.getLastRow()).getValues();
rowIndex.push(validWeekIndex);
}
validWeekIndex++;
}
}
I have tried different things, always using Logger.log() or Browser.msgBox() trying to identify the problem. Any ideas or workarounds? I have been stuck with this for 3 days now and can't find any solution.
I have prepared a sample sheet as well, if it is needed then I can edit it in.
Thanks in advance!
Edit:
Here is the link to the sample sheet: https://docs.google.com/spreadsheets/d/1xCZur6gpfsQFPtwKcTl0XPPfG8zlTqGVlm1GZZ8X1xM/edit?usp=sharing
I figured it out.
It was of course not the trigger, but different factors that made me think it was:
Trigger notifications: I was sure I set notification to immidiatly, but it was set to 4pm every day. That's the reason I didn't get the failure notifications.
The while loop: Because the while loop can't identify when the value from the 1D array turns up in the 2D array, it keeps running and times-out. Therefore the script runs for 5 minutes without possibility to cancel it.
I learned that Google got a quota of 30 min / day of script running time for triggers, so that's why I could only run 6 failed scripts before the quota was full and the script woulnd't run at all until the next day without me realizing it was an issue.
Edit: For future references, I simply used sourceWeekNumber.toString() to be able to get it to match with the other array, comparing a string instead of and object inside of an array.

Script gives error when spreadsheet range doesn't exist

I have this simple line of code in my Google Apps Script:
s.getRange('C2:C').clearContent();
but sometimes my spreadsheet only has one row, so C1 is there but C2:C does not exist. In such case, the script gives an error.
Does anyone know how I can achieve the same function as the above code but so that there is no error when only Row 1 exists?
I have this so far, but I don't know if there's anything wrong with it. It seems too simple:
function Test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var values = s.getRange('C:C');
var howManyRows = values.getNumRows();
if (howManyRows >= 2)
s.getRange('C2:C').clearContent();
}
}
the method getMaxRows() returns the number of available rows in a sheet, so you could use it in a condition like this :
if(s.getMaxRows()>1){s.getRange('C2:C').clearContent()}