I'm just starting tinkering with scripts for Google Spreadsheet and I have a problem :
How to test if the type of a function's parameter is a range of cells ?
I'd like to do something like this :
if(typeof intput != "range") {
throw "input must be a range";
}
From Google's examples here (middle of the page) :
if (typeof inNum != "number") { // check to make sure input is a number
throw "input must be a number"; // throw an exception with the error message
}
So this seems to be the right way to test the type of a variable. But I don't know how to test if the type is a range of cells.
It'd be even better if I could specify if the range is one or two dimensions.
You can specify ranges by their row and column numbers, or by using A1 notation.
Run a test deploymentOpen the script project containing your add-on. Click Deploy > Test deployments. Under Saved Tests, select the radio button next to the saved test deployment you want to run and click Execute.
flush() Applies all pending Spreadsheet changes. Spreadsheet operations are sometimes bundled together to improve performance, such as when doing multiple calls to Range. getValue().
A range of cells is just a Array (multidimensional array) Javascript has a problem in that way. Array's are seen as an object. So first check if you have the "object" type and then you could test like this.
if(typeof intput=="object"&&intput.length!=undefined) {
//input is a array
}else{
//Not a array
}
By testing a default property you can determine for certain that you have a array
A range may represent a single cell (e.g. 'A1'
) or group of cells (e.g. 'A1:A2'
).
A range is converted into a range value when it is passed as a custom function parameter (e.g. =processRangeVal(A1:A2)
).
If the range is a single cell then the range value is simply the data in that cell.
If the range is a group of cells then the range value is a 2-dimensional array. The first dimension is the rows and the second dimension the columns in each row.
To test for the range value representing a cell vs a group of cells:
function processRangeVal(rangeVal) {
if (Array.isArray(rangeVal[0])) {
// do 2d-array handling
} else {
// do cell data handling
}
}
rangeVal[0]
resolves to undefined
if the range is a single cell and the cell data does not support indexing. In this case Array.isArray(undefined)
resolves to false which is what we want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With