Hi Vladimir,
Obviously, you are trying to use the solution from this old answer by Kuba.
First of all, I would say that the old solution is not only highly inefficient, but also can easily corrupt the contents of the Notebook – for example, if you click inside of the Notebook during evaluation of the script. The dangerous is NotebookWrite part which should be rewritten using FrontEndTokenExecute["OpenCloseGroup"].
The NotebookRead part makes that solution highly inefficient and should be rewritten using CurrentValue[cellObj, "CellGroupOpen"]. But I'm not sure that this command works in Mathematica version 9.
Unfortunately, I don't have Mathematica 9 installed, so I can't test specifically for that version. I recommend rewriting at least the NotebookWrite part which is the only part of the solution that could corrupt your Notebook.