简体   繁体   中英

How to drag down a formula into empty cells (one column only)? Google Apps Script

I'm trying to do the following: 1) Check how many rows have been populated in Column A; 2) Check how many rows have been populated in Column G; 3) Drag down the formula from the last populated row of Column G into the remaining blank cells.

For example, if there are 15 rows populated in column A, but column G only has 10 cells containing the formula, I would like to drag down the formula from cell G10 down through G15 (assuming G11-15 are all empty)

Below is my code, for some reason it isn't working (keeps getting stuck in then "Preparing for execution..." screen when I run it)

Any help is much appreciated!!

function dragdown() {

var sh=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var lastpopulatedrowForm = sh.getRange("A1:A").getLastRow();
var lastpopulatedrowManual = sh.getRange("G1:G").getLastRow();

    for (var i=1;i<=lastpopulatedrowForm;i++) {

         var emptyrange= sh.getRange(lastpopulatedrowManual, 6, i, 1);

         if (emptyrange.isBlank()) {

         var copyformulacell = sh.getRange(lastpopulatedrowManual,6,1,1);
         var getformula = copyformulacell.getFormulaR1C1();
         emptyrange.setFormula(getformula);

                                    }
       }
  }

How about this modification? In this modification, copyTo() was used for copying the formula of the last row of column "G". The flow of modified script is as follows. Please think of this as just one of several answers.

  1. Retrieve values of column "A" and "G".
  2. Retrieve last rows of both column "A" and "G".
  3. Copy the formula at the last row of column "G" to the empty rows after the last row of column "G".

Modified script:

function dragdown() {
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
  var lastpopulatedrowForm = sh.getRange("A1:A").getValues();
  var lastpopulatedrowManual = sh.getRange("G1:G").getValues();
  var lastRowOfColA = 0;
  var lastRowOfColG = 0;
  for (var i = lastpopulatedrowForm.length - 1; i >= 0; i--) {
    if (lastRowOfColA === 0 && lastpopulatedrowForm[i] != "") {
      lastRowOfColA = i + 1;
    }
    if (lastRowOfColG === 0 && lastpopulatedrowManual[i] != "") {
      lastRowOfColG = i + 1;
//      break; // If lastRowOfColA is always larger than lastRowOfColG, you can use this line.
    }
  }
  if (lastRowOfColA > lastRowOfColG) {
    var src = sh.getRange(lastRowOfColG, 7);
    var dst = sh.getRange(lastRowOfColG + 1, 7, lastRowOfColA - lastRowOfColG, 1);
    src.copyTo(dst, SpreadsheetApp.CopyPasteType.PASTE_FORMULA);
  }
}

Reference:

If I misunderstood your question and this was not the result you want, I apologize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM