3

I'm trying to get a Google sheets apps script to work for an IMPORTXML I'm using.

A1
=importxml("http://www.nfl.com/liveupdate/scorestrip/ss.xml","//@q")

A2
=importxml("http://www.nfl.com/liveupdate/scorestrip/ss.xml","//@h")

The data fills from A1:B16

According to a script I found on web to have it auto refresh:

function getData() {
  var queryString = Math.random();

  var cellFunction1 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A1').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A2').getValue() + '")';
  SpreadsheetApp.getActiveSheet().getRange('C1').setValue(cellFunction1);

  var cellFunction2 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A4').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A5').getValue() + '")';
  SpreadsheetApp.getActiveSheet().getRange('C2').setValue(cellFunction2);
}

I don't know what I'm supposed to be putting/replacing in that code with mine. If someone could help me to explain what I'm supposed to be changing to get it to work in my sheet/provide some examples of how one might look that would be a huge help.

I appreciate

Rubén
  • 34,714
  • 9
  • 70
  • 166
ATS
  • 47
  • 1
  • 1
  • 8

3 Answers3

0

You can update the function by using getFormula() then setFormula() in a time-driven trigger function. Here is a code snippet from a related SO post:

/**
 * Go through all sheets in a spreadsheet, identify and remove all spreadsheet
 * import functions, then replace them a while later. This causes a "refresh"
 * of the "import" functions. For periodic refresh of these formulas, set this
 * function up as a time-based trigger.
 *
 * Caution: Formula changes made to the spreadsheet by other scripts or users
 * during the refresh period COULD BE OVERWRITTEN.
 *
 * From: https://stackoverflow.com/a/33875957/1677912
 */
function RefreshImports() {
  var lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return;             // Wait up to 5s for previous refresh to end.
  // At this point, we are holding the lock.

  var id = "YOUR-SHEET-ID";
  var ss = SpreadsheetApp.openById(id);
  var sheets = ss.getSheets();

  for (var sheetNum=0; sheetNum<sheets.length; sheetNum++) {
    var sheet = sheets[sheetNum];
    var dataRange = sheet.getDataRange();
    var formulas = dataRange.getFormulas();
    var tempFormulas = [];
    for (var row=0; row<formulas.length; row++) {
      for (col=0; col<formulas[0].length; col++) {
        // Blank all formulas containing any "import" function
        // See https://regex101.com/r/bE7fJ6/2
        var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
        if (formulas[row][col].search(re) !== -1 ) {
          tempFormulas.push({row:row+1,
                             col:col+1,
                             formula:formulas[row][col]});
          sheet.getRange(row+1, col+1).setFormula("");
        }
      }
    }

    // After a pause, replace the import functions
    Utilities.sleep(5000);
    for (var i=0; i<tempFormulas.length; i++) {
      var cell = tempFormulas[i];
      sheet.getRange( cell.row, cell.col ).setFormula(cell.formula)
    }

    // Done refresh; release the lock.
    lock.releaseLock();
  }
}

Hope this helps.

Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91
0

I have been working on something related and finally solved it by using code from this StackOverFlow Post, but I needed to add some extra bits.

It wasn't working well for me, so I made some changes and added extra logging to make it understandable for me. Here is goes:

function RefreshImports() {
  var lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return;             // Wait up to 5s for previous refresh to end.
  
  var now = new Date();
  // Show start time on log
  Logger.log("Starting Running at " + now.toLocaleTimeString());
  
  var url = "URL OF YOUR SHEET";
  var sheetName = "NAME OF YOUR SHEET";
  
  var ss = SpreadsheetApp.openByUrl(url);
  var sheet = ss.getSheetByName(sheetName);

    var dataRange = sheet.getDataRange();
    var formulas = dataRange.getFormulas();
    var tempFormulas = [];
    for (var row=0; row<formulas.length; row++) {
      for (var col=0; col<formulas[0].length; col++) {
        // Blank all formulas containing any "import" function
        // See https://regex101.com/r/bE7fJ6/2
        var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
        if (formulas[row][col].search(re) !== -1 ) {
          tempFormulas.push({row:row+1,
                             col:col+1,
                             formula:formulas[row][col]});
          sheet.getRange(row+1, col+1).setFormula(""); //cleans up the formula
        }
        
      }
    }
    // After a pause, replace the import functions
        Utilities.sleep(500);
        for (var i=0; i<tempFormulas.length; i++) {
          var cell = tempFormulas[i];
          sheet.getRange( cell.row, cell.col ).setFormula(cell.formula);
          var nowLogger = new Date();     
          Logger.log("Update import from row " + cell.row + " col " + cell.col + " done at " + nowLogger.toLocaleTimeString());
          Utilities.sleep(1000); //adding to try to control the amount of parallel connections from the Sheet
        }
      
  
    // Show Finished time on log
  var now = new Date();
  Logger.log("Sources from URLs were last updated at " + now.toLocaleTimeString());

    // Done refresh; release the lock.
  lock.releaseLock();
  
}

Then I added the Time-Based trigger from my project in https://script.google.com/home/triggers, and that one handles the automatic update execution.

I hope this helps!

sirnejo
  • 1
  • 1
  • It is actually not working. I mean it really does not refresh the cell whereas using a random number it works: ``` function getData() { var queryString = Math.random(); var Xpath_1 = "/html/body/text()"; var importXpath_1 = '=IMPORTXML("' + 'http://www.pde-racing.com/trams/tram.php?id=999&valor=1&manega=Entrenament+1&dbTemps=Event999Ex.scdb&dbInscrits=Event999.scdb&name=&_=1616318271525' + '?' + queryString + '";"'+ Xpath_1 + '")'; SpreadsheetApp.getActiveSheet().getRange('B39').setValue(importXpath_1); } ``` – Mitteg Mar 21 '21 at 10:39
0

It is actually not working. I mean it really does not refresh the cell whereas using a random number it works:

function getData() {
  var queryString = Math.random();

  var Xpath_1 = "/html/body/text()";
  var importXpath_1 = '=IMPORTXML("' + 'http://www.pde-racing.com/trams/tram.php?id=999&valor=1&manega=Entrenament+1&dbTemps=Event999Ex.scdb&dbInscrits=Event999.scdb&name=&_=1616318271525' + '?' + queryString + '";"'+ Xpath_1 + '")';
  
  SpreadsheetApp.getActiveSheet().getRange('B39').setValue(importXpath_1);
}
Mitteg
  • 169
  • 1
  • 5
  • 15