简体   繁体   English

Google表格 - 查找数组中包含数据的最后一列

[英]Google Sheets - Find last column with data in array

I'm trying to find the last column in a range, but the problem is I can't specify the script to only check within an array instead of the entire sheet.我试图找到一个范围内的最后一列,但问题是我无法指定脚本只检查数组而不是整个工作表。 I was able to use this bit of code to find the last row but I'm having trouble understanding how this can be changed to find the column instead of row.我能够使用这段代码找到最后一行,但我无法理解如何更改它以找到列而不是行。

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);
}

Source for this code 此代码的来源

Can anyone explain to me how this function could be changed up a bit to search for the column instead of the row?谁能向我解释一下这个函数如何改变一下来搜索列而不是行?

Description描述

Finding the last row or column containing data of a range can be simplified with the use of Range.getNextDataCell().使用 Range.getNextDataCell() 可以简化查找包含范围数据的最后一行或最后一列。

Here is a spreadsheet with sparcely populated cells.这是一个包含稀疏单元格的电子表格。

在此处输入图像描述

Code.gs代码.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);
  }
}

Execution log执行日志

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

Reference参考

In your situation, how about the following modification?在您的情况下,如何进行以下修改?

Modified script:修改后的脚本:

function findLasColumn() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const range = sh.getRange("A:K");
  const offset = range.getColumn();
  const maxColumn = Math.max(...range.getDisplayValues().map(r => r.reduceRight((n, c, i) => {
    if (!n && c) n = i;
    return n
  }, null)));
  const lastColumn = maxColumn + offset;
  console.log(lastColumn);
}
  • When this script is run, from "A:K" , the last column number is returned.运行此脚本时,从"A:K"开始,返回最后一列号。
  • If you use "B:K" , the last column number is returned as the valid column number.如果您使用"B:K" ,则最后一个列号将作为有效的列号返回。

Reference:参考:

Alternative Approach替代方法

You can also use the transpose method to be able to get the last column in your range.您还可以使用转置方法来获取范围中的最后一列。

Tweaked Script:调整脚本:

function findLastColumn() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const range = sh.getRange("C1:H18");
  const data = transpose(range).map((values,index) => values[0].length ? index+range.getColumn() : null).filter(d => d); //The 'index+range.getColumn()' part returns the number of a non-empty col
  console.log(data[data.length-1]);
}

function transpose(range){
  return range.getValues()[0].map((_, colIndex) => range.getValues().map(row => row[colIndex]));
}

Sample Sheet:样品表:

在此处输入图像描述

  • After running the findLastColumn() function运行findLastColumn()函数后

在此处输入图像描述

Reference:参考:

Based on your question here , and I want to paste data in the first empty row in the range A:K.根据您的问题I want to paste data in the first empty row in the range A:K. Here is a simple solution for finding the first blank row and column.这是查找第一个空白行和列的简单解决方案。

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 === ``))+1

You can prototype a function as follows您可以按如下方式对函数进行原型设计

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();
  }              
}

and

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();
  }  
}

and then use as然后用作

const lastRow = sheet.getLastDataRow('B') // for column B, can be omitted

and

const lastCol = sheet.getLastDataColumn(5) // for row#5 can be omitted

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据列中的日期在谷歌表格中获取一组数据? - How to get an array of data in google sheets based on date in column? 如何在比谷歌表格中的其他列短的列末尾找到值的最后一个单元格? - How to find the last cell with a value at the end of a column that is shorter than other columns in Google Sheets? 在 Google App Script 中存储数组并将数组打印到 Google Sheets 列 - Storing an Array in Google App Script and Printing an Array to Google Sheets Column 将Google表格中的JSON数据放入数组中 - Putting JSON data from Google sheets into an array 更正脚本以仅发送Google表格中的最后一行数据 - Correct script to send only the last row of data in Google Sheets 在 Google 脚本编辑器(Google 表格)中按 K 列过滤数据 - Filter data by column K in Google Script Editor (Google Sheets) 如何在Google表格中的一列中获取数组的总和 - How to get the sum of an array down a column in Google Sheets 如何获取列中的值并将它们放入数组中? 谷歌表格 - How to get values in a column and put them into an array? Google Sheets Google表格脚本复制值从数组到列 - Google Sheets Script Copy Values from Array to Column 给定第一个字母和数据数组,如何生成谷歌表格列的最后一个字母? - How to generate the last letter of a google sheet column given the first letter and an array of data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM