连接谷歌表脚本中的两列

时间:2018-01-07 18:48:49

标签: javascript google-apps-script google-sheets

我正在尝试连接由,分隔的两列,并将结果发回第三列  数据如下:

colA     colb      concatenated
aa bb    ww ww     aa bb, ww ww
mm
         qq        qq
zz oo              zz oo

ss       vv zz     ss, vv zz

我收到错误Cannot read property "0" from undefined.

感谢您的帮助

function ConCat() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Elements");
    var lr = sheet.getLastRow();
    var values1 = sheet.getRange(1, 1, lr,1).getValues();  //Get vales for Column1
    var values2 = sheet.getRange(1, 2, lr,1).getValues();  //Get values for column 2
    var results = [];                               //Create a empty array to be filled concatenated elements

    //Add items to results
    for(var i=0; i<lr; i++){
        results[i] = (values1[i][0]+", "+values2[i][0]);
    }

    //Post back to column 3 starting on row 2
    sheet.getRange(2, 3, lr, 1).setValues([results]);
}

2 个答案:

答案 0 :(得分:2)

setValues想要一个二维数组。你有一个数组。变化

results [i] =(values1 [i] [0] +“,”+ values2 [i] [0]);到

results[i] = [values1[i][0]+", "+values2[i][0]];

并更改

sheet.getRange(2,3,lr,1).setValues([results]);到

sheet.getRange(2, 3, lr, 1).setValues(results);

答案 1 :(得分:0)

试试这个: results.addItem(values [i] [0] +&#39;&#39; + values [i] [1]); 要么 results.push(值[I] [0],值[I] [1]);