Simple function in Basic (Libre Office Calc)

Dear Libre Office Users
I am new in Libre Office macros, but I worked a bit with Visual Basic in MS Excel. I would like to write simple function in LO Calc, like this:

Function test()

Dim sum as Double
Dim oSheet
Dim oCell

sum=5
oSheet=ThisComponent.Sheets.getByName("Sheet1")
oCell=oSheet.getCellByPosition(3, 3)
sum=sum+oCell.getValue()

End Function

All seems to be fine (I checked it and there is no errors), but now I would like USE this. So for example I would like to place value of “sum” in some cells like D4. I have no idea how to do this. In Visual Basic it would be
suma=Read(“D4”)
but i have no idea how to do this in LO Calc. I have read “Chapter 12 Macros” in LO guide, but I did not find a solution of this simple problem.

What do you want to do (not clear to me). Do you want

  • a macro which places the result into a certain cell (then you need to use subroutine and not function) –or–
  • a user defined function, which can be use like =TEST(...) (just as existing functions). In that case you need a final assignment test = sum in your function and you could add =TEST() into any cell and you should get the value of D4 + 5 (according to sum=5 and ...CellByPosition(3, 3))

No idea where you take the =Read... from. As far as I have seen functions written in VBA, the name of the function was used on the left side of an asignment statement like a variable getting an assignment to state what result the function should return. The last actually processed statement of this kind is relevant. That’s the same with LibreOffice Basic. You need a line
test = sum
before the function exits.
To call the function in a sheet cell, again do as its done in every spreadsheet: =test() since your function has no parameter, but calculates a value by adding the hard-coded number 5 and the value of a hard-coded cell. (Cell given by hard-coded position)