// Function that triggers when an edit is made to the "Admin" or "Data Imports" sheets
function onEdit(e) {
// Check if the event object is defined
if (!e) {
Logger.log('No event object. Exiting onEdit.');
return; // Exit if the event object is undefined
}
const editedSheetName = e.source.getActiveSheet().getName();
Logger.log(`Edited sheet: ${editedSheetName}`);
// Check if the edit is on the correct sheets
if (editedSheetName === 'Admin' || editedSheetName === 'Data Imports') {
Logger.log('Calling Lookups due to edit on Admin or Data Imports');
Lookups();
} else {
Logger.log('Edit was not on Admin or Data Imports; no action taken');
}
}
// Main function to perform the data transfer
function Lookups() {
try {
const sourceSpreadsheetId = '[URL for Lookups Worksheet - Removed for security]';
const sourceSheetName = 'Admin';
const sourceSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetId);
const sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);
const sourceData = sourceSheet.getRange('A:AB').getValues();
const dataImportsSheet = sourceSpreadsheet.getSheetByName('Data Imports');
const dataImportsRange = dataImportsSheet.getDataRange().getValues();
for (let i = 1; i < dataImportsRange.length; i++) {
let destinationSpreadsheetUrl = dataImportsRange[i][1];
const includeInTransfer = dataImportsRange[i][99];
if (destinationSpreadsheetUrl && includeInTransfer.toLowerCase() === 'x') {
const match = destinationSpreadsheetUrl.match(/\/d\/([a-zA-Z0-9-_]+)/);
if (!match || !match[1]) {
Logger.log(`Invalid URL format for destination spreadsheet: ${destinationSpreadsheetUrl}`);
continue;
}
const destinationSpreadsheetId = match[1];
try {
const destinationSpreadsheet = SpreadsheetApp.openById(destinationSpreadsheetId);
const destinationSheet = destinationSpreadsheet.getSheetByName('Lookups');
destinationSheet.getRange('A:AB').clearContent();
destinationSheet.getRange(1, 1, sourceData.length, sourceData[0].length).setValues(sourceData);
} catch (error) {
Logger.log(`Failed to transfer data to workbook with ID ${destinationSpreadsheetId}: ${error.message}`);
}
Utilities.sleep(500); // Pause for 500 milliseconds
}
}
} catch (error) {
Logger.log(`Error in Lookups function: ${error.message}`);
}
}