mascip wrote:Thank you FJCC.
Any easy way to do it with Javascript functions ?
It would make life a lot easier for me, as i could just copy-paste what i already have.
Otherwise, i guess i'll have to learn OpenOffice Basic and code it all over again.
See
Using javascript functions in calc, and note especially Bernard Marcelly's caveats.
I have played with this a bit myself, and I'll illustrate some of the problems here.
Here is Basic to wrap a Javascript function to sum an array. I found it necessary to "flatten" the array, that is to put its columns end to end giving a one dimensional version.
Code: Select all
Function JSum(r) As Double
Dim oSP
Dim oScript
Dim s, flatrange
flatrange = flattenRange(r)
oSP = ThisComponent.getScriptProvider()
oScript = oSP.getScript("vnd.sun.star.script:Library1.JavaSum.js?language=JavaScript&location=document")
s = oScript.invoke(flatrange,Array(),Array())
JSum = s
End Function
Function flattenRange(r)
Dim i as Long
Dim j as Long
Dim Size(2) as Integer
Dim element
Dim n As Long
Dim v(0)
Dim aRow
Size(1) = UBound(r,1)-LBound(r,1)
Size(2) = UBound(r,2)-LBound(r,2)
'v = r(LBound(r),1)
n = 0
for i = 0 to Size(1)
for j = 0 to Size(2)
ReDim Preserve v(n)
if isNumeric(r(LBound(r, 1) + i, LBound(r, 2) + j)) then
element = r(LBound(r, 1) + i, LBound(r, 2) + j)
else
element = 0
endif
v(n) = element
n = n + 1
Next j
Next i
flattenRange = v
end function
Here is JavaSum.js, the flattened array is in ARGUMENTS, and eval() is the only way I could find to get the return value back to oScript.invoke (in the Basic), though there may well be something I don't know.
Code: Select all
x = new Array(ARGUMENTS.length);
for(i = 0;i < x.length;i++)
x[i] = parseFloat(ARGUMENTS[i]);
eval(jSum(x));
function jSum(x)
{
s = 0;
for(i = 0;i < x.length;i++)
s += x[i];
return s;
}
I have attached a spreadsheet containing this stuff, using it to add random numbers. It will give an error when first loaded, but after it loads you can do Ctrl-Shift-F9 to recalculate, though I think you'll want to save it first so it isn't read only.