Google Spreadheets Scripts: check if cell is empty

2019-02-12 22:17发布

I want to input a variable in a cell only if the cell is empty. The if statement, however, does not work. Any advice?

var ss=SpreadsheetApp.getActiveSpreadsheet();
var r=ss.getRange("'odpovědi'!A2:J");

var rws=r.getNumRows();

ax=r.getCell(rws-1, 10).getValue();

if (ax == "") {
  ax = "foo";
  r.getCell(rws-1, 9).setValue(ax);
}

3条回答
做自己的国王
2楼-- · 2019-02-12 22:45

No need to extact the value to determine if the cell is empty. Google Spreadsheet API already has a method for this: Range - isBlank method

var cell = r.getCell(rws-1, 10);

if (cell.isBlank()) {
    cell.setValue("foo");
}
查看更多
做自己的国王
3楼-- · 2019-02-12 22:49

If you already have cell value then use === or !== operators if you want avoid type conversion (where 0 == "" ).

Code snippet for decreasing not empty cell values

var sheet = ss.getSheets()[0];     
var range = sheet.getRange("E2:H5");
var currentValues = range.getValues();  

var newValues = [];
for (var row in currentValues) {
  var newRow = []; 
  for (var col in currentValues[row]) {
    if (currentValues[row][col] !==  "") { // if not empty cell
      newRow[col] = currentValues[row][col] - 1;          
    }
    else {
      newRow[col] = currentValues[row][col];
    }
  }
  newValues[row] = newRow;
}    
range.setValues(newValues);
查看更多
一纸荒年 Trace。
4楼-- · 2019-02-12 23:02

Try:

function myFunction() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getSheetByName('odpovědi')
  var lr=s.getLastRow()  
  var ax=s.getRange(lr, 10).getValue();
     if(ax == ""){
        ax = "foo";
        s.getRange(lr, 10).setValue(ax);
  }
  }
查看更多
登录 后发表回答