Fill down - Google Apps Script for Spreadsheets

后端 未结 4 1730
甜味超标
甜味超标 2020-12-13 09:34

Is there a function that can fill down data to all empty cells from the row above?

If not, could anyone help me out with a Google Apps Script (or other solution) tha

4条回答
  •  死守一世寂寞
    2020-12-13 10:31

    Here's a working script that adds a custom menu to your Google Sheet. Load the script for a Google Sheet, select a range on the sheet, and select "Fill Blank Cells" from the custom menu. Blank cells will be filled with the value of the cell above.

    function onOpen() {
      var ui = SpreadsheetApp.getUi();
      // Or DocumentApp or FormApp.
      ui.createMenu('Custom Menu')
          .addItem('Fill Blank Cells', 'menuItem1')
          .addToUi();
    }
    
    function menuItem1() {
      fillBlankWithAbove()
    }
    
    //Iterates over the range from top to bottom
    //and left to right, and fills blank cells 
    //with the value right above them.
    function fillBlankWithAbove() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var range = sheet.getActiveRange();
      Logger.log('Range height is: ' + range.getHeight());
      var values = range.getValues();
    
      var width = values[0].length;
      var height = values.length;
      Logger.log('Width is ' + width);
      Logger.log('Height is ' + height);
    
      for (var i = 0; i < width; i++) {
        var lastVal = '';
        for(var j = 0; j < height; j++) {   
          var currValue = values[j][i];
    
          var dataType = typeof(currValue);
          //Empty string check returns true if dataType
          //is a number, and value is zero.  In that case
          //we don't want to overwrite the zero, so only
          //check emptyString for string types.
          if(currValue === undefined || 
             (dataType === 'string' && currValue == '')
            )  {
            //getCell parameters are relative to the current range
            //and ones based
             var cell = range.getCell(j+1, i+1);
             cell.setValue(lastVal);
    
          }
          else {
            lastVal = currValue;
          }
        }
      }
      SpreadsheetApp.flush();
    }
    

提交回复
热议问题