2012-07-11 77 views
1

我已经构建了一个包含多个选项卡的电子表格。根据另一个选项卡上的内容更新字段

我的“来源”选项卡1包含列“ID”和“名称” 我的“目标”选项卡2包含“ID”

我试图通过行中我的目标选项卡遍历和读取Id的值,然后搜索我的Source选项卡中的Id。当我找到Id时,我想抓取'Name'字段中的值并将其添加到我的Target Tab的Id的同一行中的单元格中。

我很难通过迭代遍历一个数组的逻辑来确保我在“目标”选项卡或“目标选项卡”内容的数组中找到值。在“目标”选项卡中,可能有多个Id出现,我需要全部更新它们。

欢迎任何建议!

回答

1

这里有一个建议:

/* let us say source array with name(columnA) & ID(columnB) is array 'source' 
and target array with only IDs is array 'target', you get these with something like*/ 
    var source = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getDataRange().getValues(); 
// and 
    var target = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1].getDataRange().getValues();// if other columns, change index values in the arrays : 0=A, 1=B ... 
// then let's create a 3 rd array that will be the new target with ID + names, and call it 'newtarget' 
    var newtarget=new Array() 
// the iteration could be like this : 
      for(i=0;i<target.length;++i){ // don't miss any ID 
      for(j=0;j<source.length;++j){ // iterate through source to find the name 

      if(target[i][0].toString().match(source[j][1].toString()) == source[j][1].toString()){ 
       var newtargetrow=[source[j][0],target[i][0]] // if match found, store it with name (idx0) and ID (idx 1) 
        }else{ 
       var newtargetrow=['no name found',target[i][0]] // if no match, show it in name column 
        } 
      newtarget.push(newtargetrow);// store result in new array with 2 columns 
       } //loop source 
     } // loop target 

     /* now you have a newtarget array that can directly overwrite the old target 
     using setValues() */ 
     var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];// assuming the target sheet is sheet nr2 
     sh.getRange(1,1,newtarget.length,newtarget[0].length).setValues(newtarget); 
    // 

注意到我没有测试此代码,但它应该给你一个起点。我使用.match比较了字符串,但可以使用其他比较(数组元素之间的直接相等)......如果在工作表数据中存在意外空间的风险,也可以删除ID中的空格...我不'不知道你的数据,所以这取决于你。

+0

有很大的帮助(一如既往!)。 – 2012-07-13 16:51:49

+0

:-)谢谢,我很高兴它有帮助 – 2012-07-13 21:57:17

相关问题