首页 > 解决方案 > Google AppScript - 如何在从 ARRAY 设置值时跳过某些列[INDEXes]

问题描述

我是编码新手。

我正在尝试编辑和设置整行的值,但想跳过某些列,因为其中有公式。

简而言之:我想/必须跟踪登录和退出时间,然后将在电子表格中计算,但不应被数组覆盖。有没有办法跳过每第三个“值”/索引(因为这些是具有公式的列)?

事实上,我想跳过这些列:TOTAL、day1tot、day2tot、day3tot .... day14tot。

function editCustomerByID(id,customerInfo){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("DATA");
  const custIds = ws.getRange(2, 1, ws.getLastRow()-1, 1).getDisplayValues().map(r => r[0].toString().toLowerCase());
  const posIndex = custIds.indexOf(id.toString().toLowerCase());
  const rowNumber = posIndex === -1 ? 0 : posIndex +2; 

  Logger.log(customerInfo);
  ws.getRange(rowNumber, 2, 1, 8).setValues([[
                                              customerInfo.name, 
                                              customerInfo.total, 
                                              customerInfo.day1in, 
                                              customerInfo.day1out, 
                                              customerInfo.day1tot, 
                                              customerInfo.day2in,
                                              customerInfo.day2out, 
                                              customerInfo.day2tot   

                                            // UNTIL DAY 14     
                                            
                                         ]]);
return true;

标签: arraysgoogle-apps-script

解决方案


要跳过列,您可以将范围细分为各个范围并实现条件语句

样本:


function editCustomerByID(id,customerInfo){
  ...
  var valueArray = [
                                              customerInfo.name, 
                                              customerInfo.total, 
                                              customerInfo.day1in, 
                                              customerInfo.day1out, 
                                              customerInfo.day1tot, 
                                              customerInfo.day2in,
                                              customerInfo.day2out, 
                                              customerInfo.day2tot   

                                            // UNTIL DAY 14     
                                            
                    ]
  var startColumn = 2;
  //loop through all values
  for (var i = 0; i < valueArray; i++){
  // filter out every 3rd value
    if((i+1) % 3 != 0){
      ws.getRange(rowNumber, (startColumn + i)).setValue(valueArray[i]);
    }
  }
return true;
  • 请注意,上面的示例代码使用方法setValue()而不是setValues()
  • 执行多个请求以将值设置到单个范围的效率低于在单个请求中一次设置所有值,但是在您的情况下这是必要的,因为您所需的值范围不是连续的

推荐阅读