Using Google Apps Script, is there a way to write the values in a Google Spreadsheet array to a range without looping?
I am thinking something like the following to put one name each into cells A1:A3
function demoWriteFromArray() {
var employees=["Adam","Barb","Chris"];
ssActive = SpreadsheetApp.getActiveSheet();
rgMyRange = ssActive.getRange("A1:A3");
rgMyRange.setValue(employees)
}
Problem with above is that after execution, A1:A3
all contain ={"Adam","Barb","Chris"} and display "Adam"
.
The top answer provides a nice, compact way of writing an array to a ROW but to write to a COLUMN it is a bit harder but since that's the question here, here's a quick function to do it:
Where you'd then call the function in your code like so:
Even though it's a bit late, someone might come across this answer at some point. I wrote a function that coerces a 1-d Array into a 2-d Array (matrix), which is what is expected as a parameter to
Range.setValues()
:I can't guarantee that any values except basic data types will be preserved. The sanitization is necessary because JavaScript internally seems to replace empty values in the original Array with
null
or"null"
when it is assigned to be the element of another Array. At least, that's my experience. It works though, someone may find it useful.I improved script execution time by a factor of 10x. it works for me like this:
Range.setValue() is used for setting the same value in every cell of the range, while setValues is used to set an array of values into the corresponding cells in the range. Be aware that this method expects a multi-dimensional array, with the outer array being rows and the inner array being columns. So in your case the data should look like:
I saw this question when researching an answer for my own application. An alternative solution is to use a custom function that returns a 2D array.
Here's an example. Suppose "Adam, Barb, Chris; Aaron, Bill, Cindy" is text in A1. If you put a reference to a custom function in B1, you can fill the range B1:D2 with individual names.
Custom function written in Apps Script:
The formula in B1 referencing the custom function:
=splitNames(A1)
Note, this function will throw an exception if the cells adjacent to B1 are not empty. This could be handled with the
IFERROR
formula or possibly try/catch within the custom formula.Here are four functions: (1) setting a horizontal range of values (2) setting a vertical range of values (3) setting an area of values (4) copying an area of values and pasting it.