Why does my code pulls complete source data into the main sheet upon updating data in the source sheet

I have three source spreadsheets and I managed to consolidate data into a master sheet, but my aim is to see to see to it, whenever data is update or new row is added in any of the source spreadsheets, the master sheet must get updated as well. The current script pulls up all the data into the main sheet along with updated data or new rows added in the source sheet. Also, the trigger won’t run. I have set up onEdit function, Event – From spreadsheet

I am trying to see that any updates in the source sheets such as edit to the exiting data or deleting data or a new row is added gets appended to the main sheet. The result pulls up complete data from all the three source sheets and the new row item

// Global variable to store the last processed row for each source sheet
var lastProcessedRows = {};

// Function to consolidate data from source sheets to the main sheet
function consolidateData() {
  // Define the sources with URLs, sheet names, and ranges
  var sources = [
    { url: "https://docs.google.com/spreadsheets/d/1vi-vOGAwYwKLfBziz0LaJeL6jvDD4pifB_cmalRYSC4/edit#gid=1541407214", sheetName: "DataSheet", range: "A:J" },
    { url: "https://docs.google.com/spreadsheets/d/1RF2zGom8Gc5OGvlnm9mrIVMPQRkI58_Tj_VDAaw3bN8/edit#gid=1541407214", sheetName: "Info", range: "A:J" },
    { url: "https://docs.google.com/spreadsheets/d/17HUUp0bZGKsZa11xe-Mnapd3xtJqaCSnSUTuda09VKk/edit#gid=1541407214", sheetName: "Records", range: "A:J" }
  ];

  // Define the name of the main sheet
  var mainSheetName = "MainSheet";
  
  // Get the main spreadsheet and main sheet
  var mainSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = mainSpreadsheet.getSheetByName(mainSheetName);
  
  // Loop through each source spreadsheet
  sources.forEach(function(source) {
    // Open the source spreadsheet
    var sourceSpreadsheet = SpreadsheetApp.openByUrl(source.url);
    
    // Get the source sheet and range
    var sourceSheet = sourceSpreadsheet.getSheetByName(source.sheetName);
    var dataRange = sourceSheet.getRange(source.range);
    
    // Get the values from the source range
    var values = dataRange.getValues();
    
    // Get the last processed row for this source sheet
    var lastProcessedRow = lastProcessedRows[source.url] || 0;
    
    // Check if there are new rows to append
    if (values.length > lastProcessedRow) {
      var newData = values.slice(lastProcessedRow); // Get new rows
      mainSheet.getRange(mainSheet.getLastRow() + 1, 1, newData.length, newData[0].length).setValues(newData); // Append to main sheet
      lastProcessedRows[source.url] = values.length; // Update last processed row
    }
    
    // Update main sheet based on changes in source sheet
    updateMainSheet(mainSheet, dataRange, mainSheet.getLastRow(), source.url);
  });
}

// Function to update the main sheet based on changes in source sheets
function updateMainSheet(mainSheet, sourceRange, mainSheetLastRow, sourceUrl) {
  var mainValues = mainSheet.getDataRange().getValues();
  var sourceValues = sourceRange.getValues();
  
  // Loop through each row in the source sheet
  sourceValues.forEach(function(sourceRow, rowIndex) {
    var found = false;
    
    // Check if the row exists in the main sheet
    mainValues.forEach(function(mainRow, mainIndex) {
      if (JSON.stringify(sourceRow) === JSON.stringify(mainRow)) {
        found = true;
        return;
      }
    });
    
    // If row not found in main sheet, append it
    if (!found) {
      mainSheet.getRange(mainSheetLastRow + rowIndex + 1, 1, 1, sourceRow.length).setValues([sourceRow]);
    }
  });
}

// Function to check if an edited range is within any of the source ranges
function isInSourceRanges(range, sourceRanges) {
  for (var i = 0; i < sourceRanges.length; i++) {
    var parts = sourceRanges[i].split("!");
    var sheetName = parts[0];
    var rangeString = parts[1];
    var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getRange(rangeString);
    
    if (range.intersects(sourceRange)) {
      return true;
    }
  }
  
  return false;
}

// Trigger function to run when a change is made in any of the source sheets
function onEdit(e) {
  var editedRange = e.range;
  var sourceRanges = [
    "DataSheet!A:J",
    "Info!A:J",
    "Records!A:J"
  ];
  
  if (isInSourceRanges(editedRange, sourceRanges)) {
    consolidateData();
  }
}

New contributor

Siddharth Babu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật