[英]How to delete the empty cells in a specific column using apps script?
The goal is to delete empty cells in Column N alone, without disturbing the other columns and shift the rest of the cells upwards to obtain a compact column with just non empty cells.目标是单独删除第 N 列中的空单元格,而不会干扰其他列,并将其余单元格向上移动以获得只有非空单元格的紧凑列。 There can and will be empty cells after the result of course.当然,在结果之后可以并且将会有空单元格。 Please suggest a method请推荐一个方法
function Defaulters() {
var spreadsheet = SpreadsheetApp.getActive();
var as = spreadsheet.getActiveSheet();
//to get the last row of the Column
var lastRow = 100;
var range = as.getRange("N" + lastRow);
if (range.getValue() !== "")
{Logger.log(lastRow);}
{lastRow = range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();}
Logger.log(lastRow);
//to delete the empty cells and give a compact output of just names and emails in the Column
for (var l=lastRow; l>=3; l--)
{if(as.getRange(l,14).getValue() == "")
Logger.log(true); **//what to put here to delete this cell?**
else
Logger.log(false);**// what to put here to retain this cell?**
}
}
I'd try something like this:我会尝试这样的事情:
function myFunction() {
const sheet = SpreadsheetApp.getActiveSheet();
const data = sheet.getDataRange().getValues(); // get all data
const data_new = data.filter(row => row[13] != ''); // filter the data by column 'N'
sheet.clearContents(); // clean the sheet
sheet.getRange(1,1,data_new.length,data_new[0].length)
.setValues(data_new); // put the new data back on the sheet
}
Or even like this:或者甚至像这样:
function myFunction() {
const sheet = SpreadsheetApp.getActiveSheet();
const data = sheet.getDataRange().getValues().filter(row => row[13] != '');
sheet.clearContents().getRange(1,1,data.length,data[0].length).setValues(data);
}
If you need to keep all the table intact and remove empty cells only from column 'N' it can be done this way:如果您需要保持所有表格完好无损并仅从“N”列中删除空单元格,则可以通过以下方式完成:
function clean_column_N() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('N3:N'+sheet.getLastRow()) // get a range start from row 3
const data = range.getValues().filter(String); // get a data and remove empty elements
range.clearContent().offset(0,0,data.length).setValues(data); // put the data back on the sheeet
}
All data in column 'N' will be moved upward. “N”列中的所有数据都将向上移动。
Update更新
Modified last variant to clean any column:修改最后一个变体以清理任何列:
function main() {
clean_column('N');
clean_column('O');
}
function clean_column(col) {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange(col + '3:' + col + sheet.getLastRow());
const data = range.getValues().filter(String);
range.clearContent().offset(0,0,data.length).setValues(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.