【发布时间】:2020-11-24 00:09:21
【问题描述】:
我目前正在使用 Google 表单和 Appsheet 为我的公司创建投诉跟踪应用程序。该项目要求通过 Google 表单提交的每个投诉都有一个 ComplaintID。此 ComplaintID 的格式是当前年份,然后是投诉编号(例如,2020-001 将是 2020 年收到的第一个投诉)。根据该项目的规范,需要前导零。时间戳记录了年份,因此所有必要的数据都存在。
这是我在 howtogoogleapps.com 上找到的似乎几乎可以工作的脚本:
function addAutoNumber() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Form responses 1");
// Get the last row that has content.
var LastRow = sheet.getLastRow();
// Set the first Auto Number
var AutoNumberStart="2020-001";
//---- First run ------------
//Check if the first column is Timestamp
if (sheet.getRange(1, 1).getValue() == "Timestamp") {
// insert a column to the left and the text "ComplaintID" in the first row
sheet.insertColumnBefore(1);
sheet.getRange(1, 1).setValue("ComplaintID");
// Fix for (probably) a bug that formats the new column
// with the same format of the column used to insert it,
// in this case the column gets the date format like the Timestamp column.
// So we set the format to number
sheet.getRange("A2:A").setNumberFormat(0);
// check if there are already form responses and add numbers for them
if (LastRow>1) {
for(var ii=2; ii <= LastRow; ii++) {
sheet.getRange(ii, 1).setValue(AutoNumberStart);
AutoNumberStart="2020-"+ (parseInt(AutoNumberStart.substr(5,3)+1));
}
}
}
// ---- Add new Auto Number ----------
// Check if there is a Number in the AutoNumber column
// for the last Form Submission
if (sheet.getRange(LastRow, 1).isBlank()) {
// Check if it is the first Form submission and set the AutoNumberStart
if (LastRow == 2) {
sheet.getRange(LastRow, 1).setValue(AutoNumberStart);
} else {
// Get the Last AutoNumber from the previous row
var LastAutoNumber = sheet.getRange(LastRow-1, 1).getValue();
// Set the next AutoNumber
sheet.getRange(LastRow, 1).setValue("2020-"+ (parseInt(LastAutoNumber.substr(5,3)+1)));
}
}
}
但是,返回的是 2020-001、2020-11、2020-111、2020-1111、2020-1111 等。不完全是我需要的。如果你能帮我解决这个问题,我将永远感激不尽!
【问题讨论】:
标签: javascript google-apps-script google-sheets leading-zero autonumber