declaring and initializing a variable is as simple as:
shared numbervar x;
if you need to reset the value, say in a group heading
shared numbervar x:=0;
to access it in a formula:
shared numbervar x;
dostuff
...
x := x +1//increments it for example...once it is declared in the formula, you can use just like a field or function etc.
The more complex issue:
your subreport has several groups in it, and you want to report back on the groups individually...
You can pass a shared array, probably 2, 1 for location and 1 for value, back to the main report which can iterate through the array to find the value that it needs to display(since I doubt it needs to display all at once) or you can use a delimited string of location delimiter value diffDelimiter and use that to pass values back and forth.
As for where the subreport is, it needs to run before the display of its information in the main report. If it only runs once, its position is going to be different than if there are parameters to the subreport and it is run multiple times.
HTH