2016-03-10 12 views
0

我試圖將B和C行從「MBOM」工作表複製到「庫存」工作表,其中列H =「Y」。使用Google應用程序腳本將行復制到指定列值的不同工作表

我越來越.... TypeError:無法讀取未定義的屬性「長度」。 (第15行,文件 「守則」)

function onEdit(e){ 
 
    
 
    var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MBOM"); 
 
    var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory"); 
 
    
 
    var readinventory = sheetFrom.getDataRange().getValues(); 
 
     var target = new Array();// this is a new array to collect data 
 
     for(n=0;n<readinventory.length;++n){ // iterate in the array, row by row 
 
      if (readinventory[n][6]=="Y"){ // if condition is true copy row values to target 
 
      target.push([readinventory[n][1], readinventory[n][2]]);// copy column B and C (entire row is inventory[n]) 
 
      } 
 
     } 
 
     //Paste to another sheet from first cell onwards, using the array length of specifed columns 
 
     sheetTo.getRange(1,1,target.length,target[0].length).setValues(target); 
 
     
 
    
 
}

我在做什麼錯?預先感謝您的幫助!

+0

哪一行是第15行?有多個地方可以嘗試查看各種對象的長度。可能是readinventory,target或target [0]未定義。 – dho

+0

第15行是'sheetTo.getRange(1,1,target.length,target [0] .length).setValues(target);'。非常感謝!! – Alex

回答

0

target不是2維數組。 setValues()需要一個二維數組。

以下代碼使用內部數組,並在滿足條件時填充內部數組。然後將內部數組添加到外部數組。外部數組不斷獲取新的內部數組。無論何時添加新值,內部數組都必須重置爲空數組。

function onEdit(e){ 

    var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MBOM"); 
    var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory"); 

    var readinventory = sheetFrom.getDataRange().getValues(); 
    var target = new Array();// this is a new array to collect data 
    var innerArray = []; 

    for (n=0;n<readinventory.length;++n) { // iterate in the array, row by row 
    if (readinventory[n][6]=="Y"){ // if condition is true copy row values to target 
     innerArray = []; //Reset 

     innerArray.push([readinventory[n][1], readinventory[n][2]]);// copy column B and C (entire row is inventory[n]) 
     target.push(innerArray); 
    } 
    } 
    //Paste to another sheet from first cell onwards, using the array length of specifed columns 
    sheetTo.getRange(1,1,target.length,target[0].length).setValues(target); 
}; 
+0

我想我看到你的邏輯,但我仍然得到相同的錯誤 - TypeError:無法從未定義(最後一行代碼)讀取屬性「長度」。 – Alex

+0

看了另一篇文章後(http://stackoverflow.com/questions/28623341/cannot-read-property-length-from-undefined-line-39-file-code),我試着在最後添加一個目標檢查線。仍然沒有運氣:( – Alex

+0

'readinventory'爲空,或者沒有設置了'Y'的行;'target [0] .length'因此是'undefined',因爲'target'是一個空數組,從來沒有'你可以確保'sheetFrom'是正確的,'readinventory'有數據。 – dho

相關問題