OpenOffice.org Calc is a very powerful spreadsheet application, and it's made even more powerful by the fact that a user can write macros that will process the data that they, or other users, enter. However, that processing can only take place when the user:
- presses a button that has a macro associated with it
- carries out a predefined key stroke or causes an event such as closing the document - again each of these will need a macro associated with it
- manually runs the macro themselves
On the other hand the macro developer may, if they wish, add a listener that can monitor the contents of one or more cells and then run additional code if there is a change in the contents in any of the cells.
Adding an OpenOffice Listener from a Macro
A listener is simply a process attached to an OpenOffice object (such as a cell) which runs in the background, waiting for a defined event to occur (such as a change in the contents of the cell).
The first step is to create two global variables:
- an array for storing any cells to be monitored
- a variable for the listener itself
Next a subroutine is needed - this subroutine will add cells to the array as necessary, and then add a listener to the cell:
It's worth noting that there is not a listener specifically for cells - what's actually being used here is the OpenOffice functionality for updating charts.
The Data Changed Subroutine
When the listener is defined the prefix for the 'data changed' subroutine is also defined (in this case the prefix is CELL_), and the suffix must be chartDataChanged:
The contents of each of the monitored cells can now be processed:
Starting the Listeners
The listeners are not assigned to the cells automatically - for that a final subroutine is required:
Of course, this subroutine can then be run whenever the document is opened by assigning it to the 'Open Document' event.
Conclusion
In this tutorial listeners have only been assigned to two cells (A1 and A2) but as many cells as necessary can be used, and the final cell processing is very simple - again that can be extended as required to produce more complicated results on the spreadsheet.