jjo*_*312 2 javascript google-apps google-sheets google-apps-script
在过去的几天里,我发布了一些关于我正在开发的Google Apps脚本Web应用程序的问题.到目前为止,Serge在这里一直非常有帮助.该剧本的帖子就在这里.
我希望在该脚本中添加一列来生成uniqueID计数器,这样当提交新表单时,计数器将看到先前的唯一ID并增加1.想法将是带有标题行的空白电子表格.脚本在表单提交上运行,参见A2为空白并插入1.下一个提交的表格将在A2中看到2添加1并在A3中添加3,依此类推.
现在我正在研究计数器加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);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑(更新代码使用.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;
}
}
Run Code Online (Sandbox Code Playgroud)
确保获得一个始终是列中最后计数(最高值)的值的另一种方法是:( 代码中的注释)
当你说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.
}
Run Code Online (Sandbox Code Playgroud)