简体   繁体   English

Google 脚本表按名称获取列

[英]Google script sheets get column by name

I cannot find any google script editor code that can find the index number of a google sheet column by its name我找不到任何谷歌脚本编辑器代码可以通过名称找到谷歌表列的索引号

Already searched other problems and google documentation已经搜索了其他问题和google文档

function myFunction() 
{
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
  var rowNo = sheet.getLastRow();
  var colNo = sheet.getColumnName("Avg Price Per Seat");
  sheet.getRange(rowNo, colNo).setValue("=(E"+rowNo+"/M"+rowNo+")");
}

This should calculate the two columns E and M in the column called "Avg Price Per Seat" every time it runs这应该在每次运行时计算名为“Avg Price Per Seat”的列中的两列 E 和 M

You can get an array of all columns, and then use the column name to find the one you want.您可以获取所有列的数组,然后使用列名查找您想要的列。

var cols = sheet.getDataRange().getValues();
var colNo = cols[0].indexOf(colName);

You can use this function to get col number by col name.您可以使用此函数通过列名称获取列编号。 Just pass sheet and col name.只需传递工作表和列名。

function getColumnFromName(sheet, name) {
  var headers = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0];
  for (var i = 0; i < headers.length; i++) {
    if (headers[i] == name) return i + 1;
  }
  return -1;
}

Use as - var rowNo = getColumnFromName(sheet, 'Column Name');用作 - var rowNo = getColumnFromName(sheet, 'Column Name');

We can use findIndex too.我们也可以使用 findIndex。 In some cases, some columns contain the word we are reaching.在某些情况下,某些列包含我们正在访问的单词。

function getColumnId(sheet) {
  var data = sheet.getDataRange().getValues();
  var col = data[0].findIndex((name) => name === 'ID') + 1;
  return col;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM