如何在特定工作表而不是整个电子表格上运行此脚本?
function deleteQCOrder() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[4] == 'Delete' || row[4] == '') { // This searches all cells in columns A (change to row[1] for columns B and so on) and deletes row if cell is empty or has value 'delete'.
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
例如,如果我想在“ Sheet1” 上运行它,我会尝试:
function deleteQCOrder() {
var sheet = SpreadsheetApp.getActiveSheet();
var ss = sheet.getSheetByName('Sheet1');
var rows = ss.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[4] == 'Delete' || row[4] == '') { // This searches all cells in columns A (change to row[1] for columns B and so on) and deletes row if cell is empty or has value 'delete'.
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
但没有运行,却出现此错误:
TypeError:在对象Sheet中找不到函数getSheetByName。 (第3行,文件“删除订单号”。)
答案 0 :(得分:1)
您在代码中所做的事情是获得一个sheet
对象,该对象当前是活动工作表
var sheet = SpreadsheetApp.getActiveSheet();
然后您尝试从工作表对象中获取工作表对象,这是错误的地方
var ss = sheet.getSheetByName('Sheet1');
您需要做的是从电子表格对象中找到一个表格对象,如下所示:
function deleteQCOrder() {
//correct use of SpreadsheetApp for your case
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getDataRange();
var numRows = range.getNumRows();
var values = range.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[4] == 'Delete' || row[4] == '') {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
答案 1 :(得分:1)
您必须使用电子表格对象来获取工作表对象。在第二段代码中,您将获取工作表而不是电子表格。
您可以使用以下方法获取电子表格对象:
var ss = SpreadsheetApp.getActiveSpreadsheet();
然后您可以使用getSheetByName获取“ Sheet1”:
var sheet = ss.getSheetByName('Sheet1');