Home > front end >  Loop moving special column in multiple spreadsheets
Loop moving special column in multiple spreadsheets

Time:12-16

I want to move special column in multiple spreadsheets, how i can loop this function from ids list in one sheet?

can i loop this code so i don't need to repeat the id for each

    function moveColumn() {
var sheet = SpreadsheetApp.openById("1FoLZORyvRBTameHCdcnEParBI1ad5Vsg74uQXrV6E").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1NgqCNlkzBuxGIFLjNcuYFLKc3U_CxEQ7yB8xtw14").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1MXBjW70kfRzej4tZd72pNbFRk0RsiwxJs68ao").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1LqCTSmWGSLjPfIP7gkZJtAhYUf_VMeg3FQGg").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1iYNT5CJ4T8VfE16K2D2En4TEMjrgkZxtLZh8QI").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1HxliyDvR_i_LeXfbQdjPdHpXrVKRygu6AdTzA").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1KupXbxYs4LlkKisKnvaPRZbak8PhtHz76E2XA_U").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
var sheet = SpreadsheetApp.openById("1VBZKY3XB4icxPYAoaQpfvOuQv4bycp4W7aeZdfW0").getSheetByName("Sheet2");
var columnSpec = sheet.getRange("Z1");
sheet.moveColumns(columnSpec, 24);
}

how i can loop this function from ids list?

CodePudding user response:

function moveColumn() {
  const ids = ["1FoLZORyvRBTameHCdcnEParBI1ad5Vsg74uQXrV6E", "1NgqCNlkzBuxGIFLjNcuYFLKc3U_CxEQ7yB8xtw14", "1MXBjW70kfRzej4tZd72pNbFRk0RsiwxJs68ao", "1LqCTSmWGSLjPfIP7gkZJtAhYUf_VMeg3FQGg", "1iYNT5CJ4T8VfE16K2D2En4TEMjrgkZxtLZh8QI", "1HxliyDvR_i_LeXfbQdjPdHpXrVKRygu6AdTzA", "1KupXbxYs4LlkKisKnvaPRZbak8PhtHz76E2XA_U", "1VBZKY3XB4icxPYAoaQpfvOuQv4bycp4W7aeZdfW0"].forEach(id => {
    let sheet = SpreadsheetApp.openById(id).getSheetByName("Sheet2");
    let columnSpec = sheet.getRange("Z1");
    sheet.moveColumns(columnSpec, 24);
  })
}

CodePudding user response:

Use Array.forEach(), like this:

function moveColumns() {
  const ssIds = SpreadsheetApp.getActive()
    .getRange('Sheet2!A2:A')
    .getDisplayValues()
    .flat()
    .filter(String);
  ssIds.forEach(ssId => {
    try {
      const sheet = SpreadsheetApp.openById(ssId).getSheetByName('Sheet2');
      const columnSpec = sheet.getRange('Z1');
      sheet.moveColumns(columnSpec, 24);
    } catch (error) {
      console.log(`Error while processing ssId ${ssId}: ${error.message}`);
    }
  });
}
  • Related