Looking over the macro I suppose if the function is called again with the same combination of values (record and pages) it should return a cached result instead of adding to the total again.

I can't explain why PAGE_NR(True) didn't work. According to the documentation it should reset after each record. If it resets after each layout copy that would be a nasty bug.

Anyway, glad the SQL worked for you!