过去几天我发布了几个有关我正在开发的 Google Apps 脚本网络应用程序的问题。到目前为止,Serge 在这里非常有帮助。该脚本的帖子是 here .
我希望在该脚本中添加一列来生成 uniqueID 计数器,这样当提交新表单时,计数器将看到以前的 uniqueID 并增加 1。想法将是带有标题行的空白电子表格。该脚本在表单提交时运行,看到 A2 为空白并插入 1。下一个提交的表单将看到 A2 中的 2 添加 1 并将 3 放入 A3 中,依此类推。
现在我正在研究将单元格中的数字加 1 的计数器。我知道当我开发这篇文章时,我需要捕获最后一行,然后找到单元格值并添加到,但因为我是 GAS 的新人,所以我正在自学,所以我正在尝试慢慢构建嗯,你明白了。
这是一个基本的开始,如果这是一个正确的开始方向,我想获得一些反馈。
function counter() {
//Grabs the range and pinpoint cell
var ssRange = SpreadsheetApp.getActiveSheet().getRange(1,1,1,1);
//Grab the cell value of A1
var value = ssRange.getValue();
//if statement to check value in A1 and if it is null, undefined, false, 0, NAN
if (!value) {
//if the cell is null, undefined, false, 0, NAN sets value to 1
var setCell = ssRange.setValue(1);
}
//if not updates the cell by getting the value and adding 1 to it
else {
var updateCell = ssRange.setValue(value + 1);
}
}
编辑(更新代码以使用 .setProperty 和 .getProperty 的 Phil Bozak 提示
我仍在测试此代码如何处理插入电子表格的 MYID 是否按照您提到的那样手动更改。我需要确保 MYID 保持唯一。必须考虑这一点..这是代码..任何反馈表示赞赏!
function counter2() {
//Get the spreadsheet, range, and value of first cell in range
var sSheet = SpreadsheetApp.getActiveSheet();
var ssRange = sSheet.getRange(1,1,1,1);
var ssValue = ssRange.getValue();
var setUniqueID = ScriptProperties.setProperty("MYID",1);
var getUniqueID = ScriptProperties.getProperty("MYID");
//will set value of first cell to 1 if null, undefined, false, 0, NAN etc.. (runs in if //statement)
var setOne = ssRange.setValue(getUniqueID);
if (!ssValue) {
setOne;
}
else {
//This goes back and get the range, lastrow of range, and value of first cell in range of last row & adds 1 to that value
var setLast = sSheet.getRange(lastRow+1,1,1,1).setValue(getUniqueID + 1);
setLast;
}
}
最佳答案
另一种确保获得始终是最后计数(最高值)的值作为列中计数器的方法如下:(代码中的注释)
当您说 A 列中的值可以手动修改时,我就有了这个想法...在这种情况下,这是避免可能重复的唯一方法(但它并不能阻止拥有未使用的值...(但这如果需要的话也可以实现)
function OnForm(){
var sh = SpreadsheetApp.getActiveSheet()
var startcell = sh.getRange('A1').getValue();
if(! startcell){sh.getRange('A1').setValue(1);return}; // this is only to handle initial situation when A1 is empty.
var colValues = sh.getRange('A1:A').getValues();// get all the values in column A in an array
var max=0;// define the max variable to a minimal value
for(var r in colValues){ // iterate the array
if(Number(colValues[r][0]>max)){max=colValues[r][0]};// get the highest numeric value in th column, no matter what happens in the column... this runs at array level so it is very fast
}
max++ ; // increment to be 1 above max value
sh.getRange(sh.getLastRow()+1, 1).setValue(max);// and write it back to sheet's last row.
}
关于javascript - 唯一ID计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15397000/