I was working on this project and I wanted to make a function that displays an element of a specific column.
Now with javascript I can call any element of an array with
Array[i]
But for some reason this doesn't seem to work in Google Spreadsheets.
var MyFunction(A) {
return A[1];
}
This function yields me nothing.
EDIt: I solved it. I used this loop with a sort of double indexing:
for (var i=0; i < 37; i++) {
if (A[0][i] < max && A[0][i] != 0) {
var max = A[0][i];
};
};
A[0][0] is the first element if I select a row vector in spreadsheet. For example, If I select A2:A5 as A, A[0][0] will give me the value of cell A2! Thanks for the help!
I was working on this project and I wanted to make a function that displays an element of a specific column.
Now with javascript I can call any element of an array with
Array[i]
But for some reason this doesn't seem to work in Google Spreadsheets.
var MyFunction(A) {
return A[1];
}
This function yields me nothing.
EDIt: I solved it. I used this loop with a sort of double indexing:
for (var i=0; i < 37; i++) {
if (A[0][i] < max && A[0][i] != 0) {
var max = A[0][i];
};
};
A[0][0] is the first element if I select a row vector in spreadsheet. For example, If I select A2:A5 as A, A[0][0] will give me the value of cell A2! Thanks for the help!
Share Improve this question edited Feb 28, 2017 at 17:59 Captain G asked Feb 27, 2017 at 0:49 Captain GCaptain G 31 gold badge1 silver badge3 bronze badges 2- Did you try my code and was it what you needed? – ReyAnthonyRenacia Commented Feb 27, 2017 at 18:10
- I found how to do it! – Captain G Commented Feb 28, 2017 at 14:28
2 Answers
Reset to default 1Try this instead:
var MyFunction(A) {
return A[0];
}
The assumption I making here is you are trying to return the first element in the index. In javascript Array index starts at 0 and not 1.
It doesn't work that way. You have to first allow access to the spreadsheet then tell Apps Script which Spreadsheet you're working on through openById. After that you can now access the data. Here's a simple code snippet for you. I'm using the standalone mode. There maybe other ways of doing this.
We're going to access this sheet. I've included the index numbers so you can easily understand:
Then we create a function named fetchValue
which accepts 2 parameters- the row and the column.
We execute main
function which makes calls to fetchValue
.
function main(){
Logger.log("the value returned was "+ fetchValue(1,1) ); //returns las vegas
}
function fetchValue(row,col) {
var sheet = SpreadsheetApp.openById("SPREADSHEET_ID_HERE");
var data = sheet.getDataRange().getValues();
return data[row][col];
}
We then view the Logs if it returned the value of index 1,1 which is las vegas
.
Make sure the row and column you pass to fetchValue
is within range else it will return errors.