我修改了一个我最近回答的类似脚本,它应该可以满足您的需求。我没有测试,但你可以试一试。有一些评论可以解释这个想法......它可能需要一些调试。
编辑:我玩弄了这个并对其进行了更多调试;-)所以它现在似乎可以根据需要工作 - 这是我的测试表的链接
function xxx(){
/* we have an array 'keysheet'
and an array datasheet , you get these with something like*/
var keysheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getDataRange().getValues();
// and
var datasheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1].getDataRange().getValues();// if other columns, change index values in the arrays : 0=A, 1=B ...
// the iteration could be like this :
for(i=0;i<datasheet.length;++i){ // don't miss any data
for(j=0;j<keysheet.length;++j){ // iterate through keysheet to find the keys
for(k=1;k<keysheet[0].length;++k){ // iterate in keysheet row to check every column except first one
var key = keysheet[j][k]
Logger.log(k+' '+key+" "+datasheet[i].toString().match(key))
if(datasheet[i].toString().match(key) == key){// check whole rows to find if key is in data
var x = datasheet[i].shift();
datasheet[i].unshift(keysheet[j][0]) // if match found, replace first element in datasheet with fisrt element in keysheet
break // if found break k loop maybe you should also break j loop ?
}
}
} //loop keysheet
} // loop datasheet
/* now you have a modified datasheet array that can directly overwrite the old datasheet
using setValues() */
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];// assuming the datasheet sheet is sheet nr2
Logger.log(datasheet)
sh.getRange(1,1,datasheet.length,datasheet[0].length).setValues(datasheet);
}
//