The problem is simply that sometimes the module's output frequency doesn't change.
That code will only set the modules output frequency to one value once per run only. Therefore if you run the code again it will not change. Only when you power it down will it change.
but sometimes things work.
That points to decoupling problems. Where are the output wires going to? Maybe this is causing interference that is being picked up. I would add extra decoupling capacitors to the supply.