由于您正在制定一个假设列标题可以位于不同位置的脚本,因此我建议使用setFormulas
而不是 R1C1 版本,因为它必须使用相对于标头位置的偏移量。
请参阅下面的大修脚本:
function trainingDays(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName('sheet1');
// search headers (converted to separate function to return row and column)
const [tfRow, tfCol] = getLocationOfText(ws, 'Training Days');
const [tfTYNRow, tfTYNCol] = getLocationOfText(ws, 'Training: Yes or No');
// get columns only for other headers
const [, tfRDACol] = getLocationOfText(ws, 'Race Date Announced');
const [, tfRDCCol] = getLocationOfText(ws, 'Race Date Commenced');
const [, tfTDECol] = getLocationOfText(ws, 'Training Date Ended');
// convert number to letter for formula substition later
const tfRDA = String.fromCharCode(96 + tfRDACol).toUpperCase();
const tfRDC = String.fromCharCode(96 + tfRDCCol).toUpperCase();
const tfTDE = String.fromCharCode(96 + tfTDECol).toUpperCase();
// offset lastRow with row index since data is not starting at 1
const lastRow = ws.getLastRow();
const tfTYNVal = ws.getRange(tfTYNRow + 1, tfTYNCol, lastRow - tfTYNRow, 1)
.getValues();
// placeholder for output
var output = [];
// generate an array with the formula with each value in Yes/No column
tfTYNVal.forEach((cell, index) => {
// get row by offsetting index with row of header (+1 due to 0-indexing)
var row = (tfTYNRow + index + 1);
if(cell == 'Yes')
output.push([`=NETWORKDAYS(${tfRDA}${row}, ${tfTDE}${row},)`]);
else if(cell == 'No')
output.push([`=NETWORKDAYS(${tfRDA}${row}, ${tfRDC}${row},)`]);
// write blank if not yes or no (to avoid setFormulas from breaking)
else
output.push(['']);
});
// I personally avoided using R1C1 version since that uses offsets on range
// It will be an issue when header location is changed since it will conform
// to the offset given based on your original header location
ws.getRange(tfRow + 1, tfCol, lastRow - tfRow, 1).setFormulas(output);
}
function getLocationOfText(sheet, text) {
const tf = sheet.createTextFinder(text);
tf.matchEntireCell(true).matchCase(false);
const tfNext = tf.findNext();
return [tfNext.getRow(), tfNext.getColumn()]
}
输出1:
输出 2(不同的列位置):