更新基于另一个选项卡上的内容的场(Updating a field based on content

2019-07-30 09:12发布

我已经建立了多个选项卡的电子表格。

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

我试图通过行中我的目标选项卡遍历和读取ID的值,然后搜索我的源标签的标识。 当我找到了身份证,我要抢在“名称”字段中的值,并将其添加到单元格在同一行上我的目标标签的ID的。

我有一个很难穿过一个阵列迭代并确保我发现在任一目标选项卡或目标选项卡内容的阵列的值的逻辑工作。 在目标选项卡,有可能是一个id多于一个的发生,我需要全部更新。

欢迎大家提出意见!

Answer 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,如果有不需要的空间中的纸张数据的危险......我不知道你的数据,所以它给你。



文章来源: Updating a field based on contents on another tab