我試圖找到一個范圍內的最后一列,但問題是我不能指定腳本只檢查陣列而不是整個作業表。我能夠使用這段代碼找到最后一行,但我無法理解如何更改它以找到列而不是行。
function findLastRow() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const data = sh.getRange("A:K").getValues();
const mR = sh.getMaxRows();
const indexes = [];
data[0].forEach((_,ci)=>{
let col = data.map(d => d[ci]);
let first_index = col.reverse().findIndex(r=>r!='');
if(first_index!=-1){
let max_row = mR - first_index;
indexes.push(max_row);
}
});
last_row = indexes.length > 0 ? Math.max(...indexes) : 0;
console.log(last_row);
}

代碼.gs
function test() {
try {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
let range = sheet.getRange("A1:D10");
let lastRow = range.getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
console.log("lastRow = " lastRow);
range = sheet.getRange("A1:E5");
lastColumn = range.getNextDataCell(SpreadsheetApp.Direction.NEXT).getColumn();
console.log("lastColumn = " lastColumn);
}
catch(err) {
console.log(err);
}
}
執行日志
6:14:50 PM Notice Execution started
6:14:51 PM Info lastRow = 4
6:14:51 PM Info lastColumn = 4
6:14:51 PM Notice Execution completed
參考
- 運行
findLastColumn()函式后

參考:
- 在 JavaScript 中轉置陣列
- JavaScript 陣列映射()
uj5u.com熱心網友回復:
根據您的問題,這里
I want to paste data in the first empty row in the range A:K.是查找第一個空白行和列的簡單解決方案。const data = sh.getRange(`A:K`).getDisplayValues() const firstBlankRow = data.findIndex(row => row.every(cell => cell === ``)) 1 const firstBlankCol = data[0].map((_, index) => data.flatMap(i => i[index])) .findIndex(col => col.every(cell => cell === ``)) 1uj5u.com熱心網友回復:
您可以按如下方式對函式進行原型設計
Object.prototype.getLastDataColumn = function(row) { var lastCol = this.getLastColumn(); if (row==null){row=1} var range = this.getRange(row,lastCol); if (range.getValue() !== "") { return lastCol; } else { return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn(); } }和
Object.prototype.getLastDataRow = function(col){ // col in letter var lastRow = this.getLastRow(); if (col == null){col='A'} var range = this.getRange(col lastRow); if (range.getValue() !== "") { return lastRow; } else { return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow(); } }然后用作
const lastRow = sheet.getLastDataRow('B') // for column B, can be omitted和
const lastCol = sheet.getLastDataColumn(5) // for row#5 can be omitted
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/473289.html- 運行
