Google脚本搜索单列并根据结果编辑行

时间:2019-04-17 15:59:19

标签: google-apps-script google-sheets

我正在尝试制作一个脚本按钮,该按钮将遍历所有行,并且如果G中有数值,则简单地从E单元格中减去G单元格,然后清除G单元格。

我在尝试仅获取G列以查看其是否包含数值时遇到问题,通常G列将为空白

我尝试获取指定的范围,但是它不粘在G列上并且无处不在。而且我认为我可能不会采用正确的方法。现在,我只是想让带有G列中数据的单元格突出显示,所以我知道我是否还在搜索正确的单元格

function calculate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange("G1:G300");
var substring = "";

  // Get array of values in the search Range
  var rangeValues = searchRange.getValues();
  // Loop through array and if condition met, add relevant
  // background color.
  for ( i = 0; i < lastColumn - 1; i++){
    for ( j = 0 ; j < lastRow - 1; j++){

      if(rangeValues[j][i] != ""){
        sheet.getRange(j+1,i+7).setBackground("#cc4125");
      }; 
    };
  };
};

2 个答案:

答案 0 :(得分:2)

尝试一下-

function calculate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var sValues = sheet.getDataRange().getValues();

  // E = 5, in array it is 4
  // G = 7, in array it is 6

  // Loop through array and if condition met, do stuff
  sValues.forEach(function(row, i) {
    if (row[6] != '') {
      row[4] = row[4] - row[6];
      row[6] = '';
      sheet.getRange(i + 1, 7).setBackground('#cc4125');
    }
  });

  sheet.getDataRange().setValues(sValues);
}

答案 1 :(得分:0)

谢谢ra89fi,您给了我99%的所需资源,这是有效的最终结果

function calculate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var sValues = sheet.getDataRange().getValues();

  // E = 5, in array it is 4
  // G = 7, in array it is 6

  // Loop through array and if condition met, do stuff
  sValues.forEach(function(row, i) {
    if (row[6] != '') {
      row[4] = row[4] - row[6];
      row[6] = '';
      sheet.getRange(i + 1, 5).getCell(1,1).setValue(row[4]);
      sheet.getRange(i + 1, 7).getCell(1,1).setValue('');
    }
  });
}