2013-04-15 30 views
0

我使用了一個函數來檢查列的長度並在每個單元格中插入unique-id。Google應用程序腳本:刪除包含getValues中字符串的行

var sh = SpreadsheetApp.getActiveSheet(); 
var dataincol = sh.getRange(1,8,sh.getMaxRows(),1).getValues(); //getRange row, column, numRows, numColumns 
//thanks to Serge insas 

我的問題是,的GetValues()也需要串,我不打算和我不知道如何從我的範圍過濾器字符串。 dataincol應該只取自由單元格,忽略字符串並繼續增加數字。

在這裏,您可以看到完整的功能:

function fillRowNumber(){ 
    var col = 1 ; // this for column A ! change to your needs 
    var sh = SpreadsheetApp.getActiveSheet(); 
    var dataincol = sh.getRange(1,col,sh.getMaxRows(),1).getValues(); 
    var maxval =0 
    for(n=0;n<dataincol.length;++n){ 
    if(Number(dataincol[n][0])>maxval){ maxval=Number(dataincol[n][0])} 
    } 
    for(n=1;n<sh.getLastRow();++n){ 
    if(dataincol[n-1][0] == ''){ dataincol[n-1][0]=maxval+1;++maxval} 
    } 
    sh.getRange(1,col,sh.getMaxRows(),1).setValues(dataincol); 
} 

感謝您的幫助

+0

我不明白你的問題...你顯示* var dataincol = sh.getRange(1,8,sh.getMaxRows(),1)*但「8 「應由col替換以選擇要檢查的列。 –

+1

我也認爲我不明白這個問題。我在下面的回答可能完全錯誤或者只是文檔的命令。很難說。問題標題似乎並不涉及手頭的問題......或者是否? – Jonathon

+0

8代表電子表格中的一個欄。 – venumaer

回答

0

兩個號碼驗證我經常使用的有:parseInt(val) == val這是一個值檢查和val.toString().match(/[0-9\-\.]/i) > -1)該字符串檢查。

在下面的代碼中,我使用了數組函數,而不是{}循環的double。 For循環也可以,我只是更喜歡EC5中的數組函數。

首先建立一個數組只是在欄的數值(你想用這個做別的事情了線的情況下,保存索引 - 另一種方法是過濾掉非數值)

第二修正dataincol用增加的maxval填充空格。

function fillRowNumber(){ 
    var col = 1; 
    var sh = SpreadsheetApp.getActiveSheet(); 
    var dataincol = sh.getRange(1, col, sh.getMaxRows(), 1).getValues(); 
    var maxval = 0; 

    var map = dataincol.map(function(row) { 
    // fill an array with numbers where numbers exist in data otherwise 0 
    return (parseInt(row[0],10) == row[0]) ? row[0] * (row[0].toString().match(/[0-9\-\.]/i) > -1) : 0; 
    }); 

    maxval = Math.max.apply(Math, map); // Mathmatical maximum 

    dataincol = dataincol.map(function(row, index) { 
    if (row[0] == '') { 
     maxval += 1; // increment maximum value 
     // if blank cell then add new maximum value 
     return (row[0] == '') ? [maxval] : [row[0]]; // if you add [&& index < sh.getLastRow()] to the conditional it restricts it to the original range of used cells not the maximum 
    } else { 
     // leave cell intact 
     return [row[0]]; 
    } 
    }); 

    sh.getRange(1, col, sh.getMaxRows(), 1).setValues(dataincol); 
} 

我並不清楚,如果你想保持整個片或只是最初輸入數據的範圍內添加最大值。嘗試替代我注意代碼註釋line 18

相關問題