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

一笑奈何 提交于 2019-11-30 23:09:34

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!