我是脚本编程的初学者,我想编写一个脚本以获得自动 ID(日期+大写字符)。
脚本没有 IF 函数也可以。但是,我的脚本仍然存在一些问题。我没有成功使用函数 IF 的条件来递增字符。
function onFormSubmit(e) {
//Déclaration des variables
var SheetResponse = SpreadsheetApp.getActiveSheet();
var DerniereLigne = SpreadsheetApp.getActiveSheet().getLastRow();
var DateToday = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'ddMMYY');
//Intégration du suffixe alphabétqiue pour l'ID
// If cells value (A.n)=(A.n-1) then character of cells "N.n" is incremented until "Z" (with n is number of LastRow)
if (SheetResponse.getRange(DerniereLigne,2).getValue() == SheetResponse.getRange(DerniereLigne-1,2).getValue()) {
var AlphaNumber = SheetResponse.getRange(DerniereLigne-1,15).getValue().charCodeAt(0);
var NextCode = AlphaNumber + 1;
// Si Code (Z) alors restart to "A"
if (NextCode > 90) {nextCode = 65;}
var NextAlpha = String.fromCharCode( NextCode );
}
// If not cells (N.n) is set to "A"
else {NextAlpha = "A";}
//Création de l'ID dans la derniére ligne et colonne "N"
SheetResponse.getRange(DerniereLigne,14).setValue(DateToday + NextAlpha);
SheetResponse.getRange(DerniereLigne,15).setValue(NextAlpha);
}
拜托,有人可以帮助我吗? 提前谢谢你。
最佳答案
这是一个按字典顺序返回下一个字符串的函数: 'A' -> 'B' -> ... 'Z' -> 'AA' -> 'AB' -> 'AC' -> ... 'AZ' -> 'BA' -> 'BB' -> ... 'ZZ' -> 'AAA' 等
function nextString(str) {
if (! str)
return 'A' // return 'A' if str is empty or null
let tail = ''
let i = str.length -1
let char = str[i]
// find the index of the first character from the right that is not a 'Z'
while (char === 'Z' && i > 0) {
i--
char = str[i]
tail = 'A' + tail // tail contains a string of 'A'
}
if (char === 'Z') // the string was made only of 'Z'
return 'AA' + tail
// increment the character that was not a 'Z'
return str.slice(0, i) + String.fromCharCode(char.charCodeAt(0) + 1) + tail
关于javascript - 使用 JavaScript 将字母字符递增到下一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32157500/