如果值不存在,则将值复制到电子表格中-Google脚本

时间:2018-11-29 10:46:48

标签: javascript google-apps-script

我正在尝试:

  1. 进入云端硬盘文件夹并检索现有电子表格的spreadSheetID
  2. 进入每个电子表格并获取一些数据
  3. 将该数据复制到TargetSheet
  4. 在数据不存在的情况下

从1-3开始,我没有任何问题,但是如果数据已经存在,我将无法正确搜索和匹配。

到目前为止,这是我的代码。如果我在同一数据集上运行两次代码,则某些数据应在不应该复制的情况下被复制,因为它们已经存在。

有什么帮助吗?

function getReportData() {

//Sources
var reportFolder = DriveApp.getFolderById('ReportFolderID') // Get Status reports folder
var reportsList = reportFolder.getFiles(); //Returns FileIterator object
var spreadSheets = [];
var targetSSheet = SpreadsheetApp.openById('TargetSheetID');
var targetSheet = targetSSheet.getActiveSheet();
var lastRow = targetSheet.getLastRow();

var searchRange = targetSheet.getRange(2, 1, lastRow, 2);
var searchRangeV = searchRange.getValues();
var allStatuses = [];


//Populate the reportSheets list with latest report sheet IDs
while (reportsList.hasNext()) {
    var reports = reportsList.next(); //Object of type file
    spreadSheets.push(reports.getId());
}


// Loop through the list of report sheets
for (i = 0; i < spreadSheets.length; i++) {
    var spreadSheet = SpreadsheetApp.openById(spreadSheets[i]);
    var activeSheet = spreadSheet.getActiveSheet();
    var individualStatus = [];


    // Gets project report data
    var projectName = activeSheet.getRange("B3:B4").getValue();
    var reportDate = activeSheet.getRange("I3:I4").getValue();
    var projectStatus = activeSheet.getRange("G9:i9").getValue();

    // Creates reports array
    individualStatus.push(reportDate, projectName, projectStatus);

    allStatuses.push(individualStatus)

}

   //Cleans the status array of existing ones
for (j = 0; j < allStatuses.length; j++) {

    var searchKey = allStatuses[j][0] + allStatuses[j][1];
    searchKey

    Logger.log(searchKey)

    for (k = 0; k < searchRangeV.length; k++) {

        var matchKey = searchRangeV[k][0] + searchRangeV[k][1];

        if (searchKey == matchKey) {
            allStatuses.splice(j, 1)
            break;
        } else {
            Logger.log(searchKey)
            Logger.log(matchKey)
        }

    }
}

//Copies the data to Target Sheet
for (var project = 0; project < allStatuses.length; project++) {
    //Gets the last row each time it goes through the loop
    var latestRow = targetSheet.getLastRow();
    var lastColumn = targetSheet.getLastColumn();

    for (var status = 0; status < allStatuses[project].length; status++) {

        targetSheet.getRange(latestRow + 1, status + 1, 1, 1).setValue(allStatuses[project][status])


    }
}

}

0 个答案:

没有答案