GetCell - > GetValue - > SetValue失败

时间:2015-10-11 12:42:26

标签: google-apps-script google-sheets setvalue getvalue

我想让下面提到的代码工作,但它没有 - 当我运行它时没有任何反应(也没有错误),这意味着用户名(sUserName)没有保存在电子表格中...而且我不明白为什么列不能以2,3,4开始(然后时间戳可以保留在第1列中)而不是1,2,3 - 如果是这样我会收到错误。

以下是代码:

 var userNameColumn = 1; //Column where the user name is written 
 var subTypeColumn = 2; //Column where the submitter type is written ex. "Requester"
 var sUserNameColumn = 3; //Column where the user name is saved

function saveUserName() {
 var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
 var rows  = sheet.getDataRange();
 var numRows = rows.getNumRows();

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

 var userNameCell = rows.getCell(i, userNameColumn);
 var subTypeCell = rows.getCell(i, subTypeColumn);
 var sUserNameCell = rows.getCell(i, sUserNameColumn);

  if(sUserNameCell.isBlank() && subTypeCell.getValue() === 'Requester') {
sUserNameCell.setValue(userNameCell)
  };  

 }
}  

以下是我的电子表格和代码的链接:

Google Spreadsheet

1 个答案:

答案 0 :(得分:1)

看看这是否有帮助

function saveUserName() {

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var rows = sheet.getDataRange().getValues();
for (var i = 1; i < rows.length; i++) {
    var userNameCell = rows[i][1];
    var subTypeCell = rows[i][2];
    var sUserNameCell = rows[i][3];
    if (!sUserNameCell && subTypeCell === 'Requester') sheet.getRange(i+1,4).setValue(userNameCell)
    }
}