簡體   English   中英

在忽略空單元格的同時填寫公式 - Google 腳本

[英]Fill Down Formula while ignoring empty cells- Google Scripts

我正在嘗試編寫一個腳本來替換以下公式:

=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))

到目前為止,這是我所在的位置:

function Formula_Columns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  ss.getRange("BP3").setFormula("=BM3 + BN3");
  var lr = ss.getLastRow();
  var fillDownRange = ss.getRange(3,68,lr-2);
  ss.getRange("BP3").copyTo(fillDownRange);
}

我想要發生的是,當日期輸入 BM 列時,公式會將 BM 列中的日期與 BN 列中設置的時間組合起來,並將其放入 BP 列。 僅當 BM 中的單元格中有日期時,我才需要腳本將 function 添加到 BP 中。 正如現在編寫的腳本,如果 BM 和 BN 列中沒有分別輸入日期和時間,它會輸入 12/30/1899 0:00:00。 (見下面的截圖)

我將不勝感激。 先感謝您。

在此處輸入圖像描述

我看到了三種解決方法。 請參閱以下方法:

腳本:

// Copying just the displayed values and returning the combined values
function writeValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var dates = ss.getRange(3, 65, lr - 2, 2).getDisplayValues();
  dates = dates.map(row => { 
    // if BM and BN is present
    if(row[0] && row[1]) 
      return [row[0] + ' ' + row[1]]; 
    // else, return blank
    else
      return [''];
  });
  ss.getRange(3, 68, dates.length, dates[0].length).setValues(dates);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Writing the ARRAYFORMULA on BP3 
// Then set the formatting of the column to Date Time
function writeArrayFormula() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  ss.getRange(3, 68).setFormula(`=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Copying formula to all cells in the column until last row of column BM
function writeFormulaPerCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var colValues = ss.getRange("BM3:BM" + lr).getValues();
  var colLastRow = lr - colValues.reverse().findIndex(cell => cell[0] != '');
  // if BM and BN is present, populate
  ss.getRange(3, 68, colLastRow - 2, 1).setFormulaR1C1(`=IF(AND(R[0]C[-3] <> "", R[0]C[-2] <> ""),  R[0]C[-3] + R[0]C[-2], "")`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

比較:

輸出

筆記:

  • 使用writeValuesOnly不會在更新BMBN時自動更新值。
  • 如果你想使用writeFormulaPerCell ,你需要使用setFormulaR1C1而不是因為當它被復制到其他行/列時,公式會根據范圍自動調整。
  • 不使用setNumberFormat (或不格式化范圍輸出)可能會產生意外結果,例如改為顯示 float 數據類型。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM