I have been playing around with Google Apps Script today and I am trying to code some custom spreadsheet functions. I have done some searching but cannot find an answer to my query.
I know that on a Google Spreadsheet you can use ImportRange in a cell on a spreadsheet like this:
=ImportRange(spreadsheet_key;sheet!range_of_cells)
My questions are is it possible to do something similar in a Google Apps Script and if so, how?
I want to import a range of cells from a sheet on another spreadsheet (not a sheet on the spreadsheet where the script will reside).
I needed to do this recently. This is what I came up with, simply hard-coding the spreadsheet key and range into ahab's
myImportRange
functionIn my case I have a set of private sheets, an intermediate sheet that uses the regular
myImportRange
and VMERGE with some SQL to combine selections from the private sheets into the intermediate sheet, and then a public sheet that simply has one cell containing= myScriptedImportRange( GoogleClock() )
Note that there is a similar approach here: https://stackoverflow.com/a/11857014
Note also that the
ImportRange
function and related functions often have a problem of not displaying the imported data when the origin workbook(s) is/are not open. A simple way around this has been described in a comment here: https://stackoverflow.com/a/11786797It seems Google, in their infinite wisdom, has altered the behavior of openById and similar functions. They are no longer allowed in the context of custom functions.
See https://code.google.com/p/google-apps-script-issues/issues/detail?id=5174 for more details.
They suggest using IMPORTRANGE as a workaround, but as previously mentioned, this needs to be called within a cell.
Our solution was to use IMPORTRANGE in the sheet, and pass the acquired data into our custom function, as the data set was small. I hope this information helps!
Yes, this is perfectly possible. You just need to call
SpreadsheetApp.openById
and then get the desired sheet and ranges normally.Please take a look at the documentation :
range.getValues()
andrange.setValues()
are very basic GAS methods and are pretty well described.Read the tutorial as well.