Home > Mobile >  Combine multiple functions in one script in Google sheets
Combine multiple functions in one script in Google sheets

Time:04-30

I'm using code to pull data from multiple sheets. The code is working fine, but I need to pull data from more than one location. I'd like to pull it all at once. The code below works fine to pull the ImportFALLOBS data (first function), but won't execute the ImportSPRINGOBS function.

const ids = [
  '1-PzUz2dlsLwA7lcndyWUZk4olgccE31jje8_JakZxXQ'
  
]
function ImportFALLOBS() {
  let result = []
  ids.forEach((id, i) => {
    let [headers, ...data] = SpreadsheetApp.openById(id).getSheetByName('FALL OBS').getRange(5,1,1,13).getValues()
    if (i == 0) { result.push(headers.flat()) }
    data.forEach(r => result.push(r))
  })
  var master = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FALLOBSIMPORT') 
  master.clearContents()
  master.getRange(2, 1, result.length, result[0].length).setValues(result)
}

function ImportSPRINGOBS() {
  let result = []
  ids.forEach((id, i) => {
    let [headers, ...data] = SpreadsheetApp.openById(id).getSheetByName('SPRING OBS').getRange(5,1,1,13).getValues()
    if (i == 0) { result.push(headers.flat()) }
    data.forEach(r => result.push(r))
  })
  var master = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SPRINGOBSIMPORT') 
  master.clearContents()
  master.getRange(2, 1, result.length, result[0].length).setValues(result)
}

CodePudding user response:

You can make your code smaller and faster by combining the common parts and just change the sheet names:

function ImportOBS() {
  const sheetNames = ['FALL OBS','SPRING OBS'];
  const importNames = ['FALLOBSIMPORT', 'SPRINGOBSIMPORT'];

  sheetNames.forEach((sheetName,i)=>{
      let result = []
      ids.forEach((id, i) => {
      let [headers, ...data] = SpreadsheetApp.openById(id).getSheetByName(sheetName).getRange(5,1,1,13).getValues()
      if (i == 0) { result.push(headers.flat()) }
         data.forEach(r => result.push(r))
      })
      var master = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(importNames[i]) 
      master.clearContents()
      master.getRange(2, 1, result.length, result[0].length).setValues(result);
  })  
}

and now you have only one function: ImportOBS

  • Related