javascript 如何使用Google表格脚本更改表中的特定值

wkyowqbh  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(121)

我是非常新的谷歌脚本和小时后,似乎我非常接近,但最后我请求您的帮助。
我的表包含6列,但超过1000行。我想选择一个特定的行,并希望更改6列中的一列。我设法找到了我要查找的行,但现在我在更新值时卡住了,因为我不知道“过滤结果”的范围。
到目前为止,我已经......请在代码中找到注解:

function useDataRange () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "PlanningX";
  var rows = ss.getSheetByName(sheetname).getDataRange().getValues();

  var filteredRows = rows.filter(function(row) {
    var ccTitle = row[2]; // my costcenter 
    var mmMonth = row[1]; // my month by name
    var searchTitle = '03.008 Bahntickets';
    var searchMonth = 'April';
    
    // because of my data structure I got 1 result (row) after this IF conditions

    if (ccTitle === searchTitle && mmMonth === searchMonth) {
      return row
    }
  })
  Logger.log(filteredRows); // yep,  this works as expected, I got only 1 row back.

  /* -----------------------------------------------------------
    Now I try to change the value in this row at column 4 to another value
    but because I don't know the range, I cannot set the value */

  filteredRows.forEach(function(row) {
    var cell = (row[4]) // this is the row number (4) I try to update
    var cell = newValue;
    var newValue = 'MY NEW VALUE'; // now I get stuck

  })

}

第一节第一节第一节第一节第一次

sgtfey8w

sgtfey8w1#

从你下面的脚本中,

filteredRows.forEach(function(row) {
  var cell = (row[4]) // this is the row number (4) I try to update
  var cell = newValue;
  var newValue = 'MY NEW VALUE'; // now I get stuck

})

如果你想用“MY NEW VALUE”的值替换列“E”的值,那么下面的修改怎么样?

发件人:

filteredRows.forEach(function(row) {
  var cell = (row[4]) // this is the row number (4) I try to update
  var cell = newValue;
  var newValue = 'MY NEW VALUE'; // now I get stuck

})

收件人:

filteredRows.forEach(function (row) {
  var newValue = 'MY NEW VALUE';
  row[4] = newValue;
});

var updatedValues = filteredRows.map(row => {
  var newValue = 'MY NEW VALUE';
  row[4] = newValue;
  return row;
});
  • 通过该修改,filteredRows中的每个row的列“E”替换为MY NEW VALUE

添加:

从你下面的回复和你添加的图片来看,
我只是附上了我的表格的截图。例如:我想将第263行E列的值从154更改为200。
下面这个修改过的脚本怎么样?

修改的脚本:

function useDataRangedd() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "PlanningX";
  var sheet = ss.getSheetByName(sheetname);
  var range = sheet.getRange("A5:E" + sheet.getLastRow());
  var rows = range.getValues();
  rows.forEach(row => {
    if (row[1] == 'April' && row[2] == '03.008 Bahntickets') {
      row[4] = 200;
    }
  });
  range.setValues(rows);
}

或者,作为另一种方法,下面的脚本如何?

function useDataRangedd() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "PlanningX";
  var sheet = ss.getSheetByName(sheetname);
  var range = sheet.getRange("A5:E" + sheet.getLastRow());
  var rows = range.getValues();
  var ranges = rows.reduce((ar, row, i) => {
    if (row[1] == 'April' && row[2] == '03.008 Bahntickets') {
      ar.push(`E${i + 5}`);
    }
    return ar;
  }, []);
  sheet.getRangeList(ranges).setValue(200);
}

相关问题