(I do not know a reasonable way how to disable macros first, and enable them later. You might try to use a global variable fed by a Sub called on a suitable document event. Every sensitive user function would then test for that variable and return a preliminary and invalid result on the first run. I did not test this idea. Below I will try to avoid the problem from the beginning.)
First of all: Your code cannot work as expected because you try to compare the numeric values you get for .CellBackColor
with strings.
Secondly: Even the working variant
getColor = Switch(bgcolor = 16776960, "yellow", _
bgcolor = 43315, "green", bgcolor = 16711680, "red")
is not recommendable insofar as you compare in every case with one of hundreds of colorcodes representing colors looking very closely like the palette color you want to identify. Palettes may change with time and from app to app. The LibO standard-palette Green
e.g. has currently (R,G,B)=(0,169,51) (your 43315) while html uses (R,G,B)=(0,128,0) (decimal 32768) for Green
.
Finally: Concerning the error message you mentioned I can only guess you are working with a buggy version. I think to remember a time when newly loaded Calc documents tried to run macros using not yet sufficiently initialized objects. This could lead to errors of that kind. Please edit your question and add information about the used version of LibO and your OperatingSystem (including the version).
Sorry. I was wrong. My current V 6.3.3 also raises an error when recalculating your function “on load”. I obviously hadn’t used macros of the king for some time. Will come back if there is a new idea.
It shouldn’t be too surprising that the ActiveSheet
which is the viewed sheet in fact not is initialized before the recalculation “on load” is finished. Anyway the user code posted above seems to be based on the misunderstanding during calculations the ActiveSheet
was the sheet for which calculation as running. You need to choose the sheet containing the cell for which the .CellBackColor
explicitly.
Start with
Function getColor(s, c, r)
Dim oDoc As Object ' define variables
Dim oSheet As Object
Dim oCell As Object
Dim bgcolor As String
oDoc = ThisComponent
oSheet= ThisComponent.getSheets(s-1)
oCell = oSheet.getCellByPosition(c-1,r-1)
bgcolor = oCell.CellBackColor
getColor = Switch(bgcolor = 16776960, "yellow", _
bgcolor = 43315, "green", bgcolor = 16711680, "red")
End Function
and find a better way to assign a color name to the RGB value. A raw suggestion you find here.