Copy formula down using script

时间:2015-05-04 19:56:05

标签: google-apps-script google-sheets

I've been working on a script (With some help from folk on SO). I have managed to create a script that imports a csv file and updates named ranges based on the imported data.

Here is an image of what I'm trying to do: enter image description here

At this point I have imported data which has been populated into columns A:G. The cells in columns H:L are formula and are based on the data in A:G. Because I have imported data the data are now longer than the formula range. If not relying on script I would just double click the small blue square at the bottom right of the highlighted cells and the formulas would copy down. This is what I'd like to have the script do once I have imported the data.

I created a range called "formula_range" which automatically updates with the length of data. "formula_range" starts in cell H3 and ends in L:N where N is the length of rows in the sheet.

"formula_range" therefore contains some populated cells with formula and then blank rows all the way to the bottom of the sheet.

I saw this SO post. So in English, my line of thinking is:

  1. Create a variable formula_range H3:L3 as a range
  2. paste formula_range to every row in formula_range
  3. Voila?

How do I get the variable formula_range if the first row in formula_range will always have the formula to be copied down. Put another way it should be fixed at H3:L3.

I tried this:

var copy_range = ss.getRangeByName("formula_range").getRange(1,5,1);
SpreadsheetApp.getUi().alert(copy_range);

My alert said "undefined" (I really wasn't sure what it would show.)

My line of thinking is not the most efficient since I am going to copy over existing formula. Perhaps there is a better way?

How do I get the first row in a named range formula_range[0]; ?

How can I use script to copy down formula in formula_range?

1 个答案:

答案 0 :(得分:4)

我认为使用内置数组公式可以更有效地实现您想要实现的目标:

https://support.google.com/docs/answer/3093275

置于H3:

= ARRAYFORMULA(DATE(A3:A,B3:B,1))

对于第3行中H到L的每个公式,用数组公式围绕它们,并使用从第3行开始的开放范围扩展参数,如上例所示