Google 应用程序:匹配 2 张表格之间的订单号并用更新日期覆盖日期列

问题描述 投票:0回答:1

我有sheet1,有17列数据。订单号在 H 列中,日期和时间在 L 列中。Sheet2 有 12 列使用 importrange 导入的数据。订单号位于 K 栏,日期和时间位于 I 栏(在脚本中显示为 L 栏,但希望将其移至 I 栏)

当sheet2订单号与sheet1订单号匹配时,我希望sheet2中的日期覆盖sheet1中的日期。

我正在尝试重新调整此脚本的用途,但不断收到错误“数据中的列数与范围中的列数不匹配。数据为 0,但范围为 1。”我是否必须重新排列我的数据列或者这可以与当前列一起使用吗?

function replaceDates() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh1 = ss.getSheetByName('FFDataPT');
  var sh1lastRow = sh1.getLastRow();
  // Sheet1!H:H values for RefNum in FFDataPT
  var sh1HValues = sh1.getRange(2, 8, sh1lastRow, 1).getValues().flat();
  // Sheet1!A:J range of data in MLB Status to replace data in FFDataPT
  var sh1AJRange = sh1.getRange(2, 12, sh1lastRow,1);
 
//Logger.log("DEBUG: sh1AJRange ="+sh1AJRange.getA1Notation());
//Logger.log("DEBUG: sh1HValues ="+sh1HValues);

  var sh2 = ss.getSheetByName('MLB Status');
  var sh2lastRow = sh2.getLastRow();
  // Sheet2!K:K values for RefNum in MLB Status
  var sh2KValues = sh2.getRange(2, 9, sh2lastRow, 1).getValues().flat();
  // Sheet2!L:L values for Updated Date in MLB Status
  var sh2LValues = sh2.getRange(2, 11 , sh2lastRow, 1 ).getValues().flat();

  // Logger.log("DEBUG: sh2KValues ="+sh2KValues);
  // Logger.log("DEBUG: sh2LValues ="+sh2LValues);

  // for every values of Sheet1!H:H refNum in FFDataPT that matches RefNum in MLB Status
  var output = sh1HValues.map(row => {
    // get position of every value in Sheet1!H:H from Sheet2!K:K
    // index is -1 if RefNum value is not found in Sht2 K:K
    var index = sh2KValues.indexOf(row);
    // if position is not -1 (means it is found)
    if(index >= 0)
      // return the corresponding value in Sheet2!L:L
      return [sh2LValues[index]];
    // return blank if value in Sheet1!L:L is not found in Sheet2!K:K
    return [];
  });

  // set Sheet1!A:L range with value of generated array 
  sh1AJRange.setValues(output);

}
google-sheets google-apps-script
1个回答
0
投票

代码的主要问题是,只要 if 语句落入 -1,就会返回

empty array
,这会导致范围内不匹配。

试试这个:

function replaceDates() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh1 = ss.getSheetByName('FFDataPT');
  var sh1lastRow = sh1.getLastRow();
  
  var sh1HValues = sh1.getRange(2, 8, sh1lastRow - 1, 1).getValues().flat();
  var sh1LRange = sh1.getRange(2, 12, sh1lastRow - 1, 1);

  var sh2 = ss.getSheetByName('MLB Status');
  var sh2lastRow = sh2.getLastRow();
  
  var sh2IDates = sh2.getRange(2, 9, sh2lastRow - 1, 1).getValues().flat();
  var sh2KValues = sh2.getRange(2, 11, sh2lastRow - 1, 1).getValues().flat();

  var output = sh1HValues.map(row => {
    var index = sh2KValues.indexOf(row);
    if (index >= 0) {
      return [sh2IDates[index]];  
    }
    return [null]; 
  });

  sh1LRange.setValues(output);
}
© www.soinside.com 2019 - 2024. All rights reserved.