.getValue() return #N/A when reading ImportXML cell sometimes

前端 未结 1 581
萌比男神i
萌比男神i 2021-01-06 17:57

I\'ve written a script that writes an ImportXML formula into a cell and then seconds later try to read and replace the cell with it\'s returning value.

The problem i

1条回答
  •  天涯浪人
    2021-01-06 18:18

    There is no way for your script to receive notification that the spreadsheet has completed recalculation. The elapsed time for recalculation is non-deterministic. Obviously, your 5 second delay is often sufficient, but sometimes the recalc takes longer.

    Replace sleep() with a retry loop to extend the window of time.

    myformula = '=ImportXML("http://api.something/01.xml","/offers/price")';
    sheet.getRange("A1").setFormula(myformula);
    while (sheet.getRange("A1").getValue() === "#N/A") {
      Utilities.sleep(5000);
    }
    sheet.getRange("A1").setValue(sheet.getRange("A1").getValue());
    

    But like I said, every time it executes I see the right value in the cell, then after I rewrite it, it gets #N/A. So in other word, if I don't rewrite the value, I see the result in less then one second in the cell. – Mille Jan 14 '13 at 19:32

    This is part of the reality of cloud computing. The spreadsheet object is being updated, and shared with all viewers who are working on cached copies of the original. Cached copies are synchronized with the original, but that isn't instantaneous. When you're viewing the sheet, you're one user. Your script is executing 'in the cloud' on another google server, and while it will eventually see the same version of the spreadsheet as you, it could take a while. Having two users making changes (you+script) requires multiple synchronization operations, so at times the affected cells will be in limbo.

    There's an open issue 1131 that is similar to this, with some work-arounds in the comments.

    0 讨论(0)
提交回复
热议问题