这是一个脚本,用于获取列中非空值的唯一列表,给定它所在的工作表和列的标题位置,使用数组存储值和 indexOf 查找重复项。然后,您可以将数组写入任何您想要的位置。
headerLocation 是一个 Location 对象:
var Location = function(sheet, row, col) {
this.sheet = sheet;
this.row = row;
this.col = col;
this.addRow = function() { this.row = this.row + 1; }
this.addCol = function() { this.col = this.col + 1; }
this.getValue = function() { return sheet.getRange(this.row, this.col).getValue(); }
this.toString = function() { return "(" + this.row + "," + this.col + ")"; }
}
这是读取列并返回唯一值的函数:
/**
* Get unique values in column, assuming data starts after header
* @param {Sheet} sheet - Sheet with column to search
* @param {object} headerLocation - row and column numbers of the column header cell
* @returns {array} list of unique values in column
*/
function getUniqueColumnValues(sheet, headerLocation) {
let startRow = headerLocation.row + 1;
let lastRow = sheet.getLastRow();
let values = [];
for (i = startRow ; i <= lastRow ; i++) {
let value = sheet.getRange(i, headerLocation.col).getValue();
if ((value != "") && (values.indexOf(value) == -1)) {
values.push(value);
}
}
return values;
}
或者,使用 Location 来查找值:
function getUniqueColumnValues(sheet, headerLocation) {
let values = [];
let searchLocation = new Location(sheet, headerLocation.row + 1, headerLocation.col);
let lastRow = sheet.getLastRow();
while (searchLocation.row <= lastRow) {
let value = searchLocation.getValue();
if (values.indexOf(value) == -1) {
values.push(value);
}
searchLocation.addRow();
}
return values;
}