To call a Calc function from user code you need to create a FunctionAccess object and use its CallFunction method.
You should study the famous texts by Andrew Pitonyak to learn more about the usage of the API. See this page and subchapter 6.28 of the “Useful Macro Information” e.g. concerning this subject. It’s about ‘OpenOffice’, but there is no difference in this respect.
(Editing with respect to the comments posted meanwhile:)
Just found the time to test a bit. Reporting the result:
The erroneous code will neither work with numbers nor with texts (strings). Rectified code will work in both cases. Example:
REM ***** BASIC *****
Option Explicit
Function customLookup(pSearchFor,pVlookupArray, Optional pZ)
' If pVlookupArray (which in fact is a text containing an address) includes the
' SheetName this name MUST NOT contain enclosing apostrophes. Simply use reasonable
' SheetName. As an alternative you may use the pZ parameter which has to give the
' number of the sheet in the way the SHEET function is counting: starting with 1.
' Therefore the pZ-1 below. If pZ and a SheetName contained in pVlookupArray are both
' given, they must be consistent.
' This user function as given here is surely of no use.
' Call VLOOKUP from a cell directly. Take it as a "Proof Of Concept".
customLookup = "fail"
On Error GoTo errorExit
Dim theSheetName As String, theSheet As Object, theVlookupArray As Object, funcAcc As Object
If Left(pVlookupArray, 1) ="$" Then
pVlookupArray = Mid(pVlookupArray, 2, 65535)
EndIf
If IsMissing(pZ) Then
theSheetName = Split(pVlookupArray, ".")(0)
theSheet = ThisComponent.Sheets.GetByName(theSheetName)
Else
theSheet = ThisComponent.Sheets(pZ-1)
EndIf
theVlookupArray = theSheet.GetCellRangeByName(pVlookupArray)
funcAcc = CreateUnoService( "com.sun.star.sheet.FunctionAccess" )
customLookup = funcAcc.CallFunction("VLOOKUP", Array(pSearchFor, theVlookupArray, theVlookupArray.Columns.Count, 0))
errorExit:
End Function
(Being back. This demo contains the code.)