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 is I often (but not always) get #N/A when replacing the cell with the fetched value. The thing is that I am able to see the correct value for a short period of time, so the value gets fetched and return correctly by ImportXML, it's when rewritten to the spreadsheets it gets messed up.
Example code:
myformula = '=ImportXML("http://api.something/01.xml","/offers/price")';
sheet.getRange("A1").setFormula(myformula);
Utilities.sleep(5000);
sheet.getRange("A1").setValue(sheet.getRange("A1").getValue());
I've noticed that when the URL has been fetch recently (and is cached internally by Google) it gets the value correct.
Suggestions on how to solve this?
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.