User Defined Functions in BASIC

Hey guys!
I’ve been trying to write some UDF’s, but due to my lack of experience with BASIC I’ve no clue what exactly went wrong.
The functions themselves work as I expect them to, but every time I open the document I use them in the following error message appears:


(The error occurs not only in line 11, but in line 18 as well)

After hitting the OK Button for eight times (I call the functions a total of seven times), the sheets appear and a part of the cells using these functions have the value “#REF!”.
To make them display the correct value again I have to edit a random cell manually and hit enter (probably triggering a refresh of all sheet calculations?).

Any help is greatly appreciated. :pray:

REM  *****  BASIC  *****

sub Main
	
end sub

function getLastSheetname()
	dim lastSheet as object
	dim lastIndex as integer

	lastIndex = ThisComponent.Sheets.Count
	lastSheet = ThisComponent.Sheets(lastIndex - 1)
	getLastSheetname = lastSheet.getName
end function


function getfirstSheetname()
	getfirstSheetname = ThisComponent.sheets(0).getName
end function

works here…

1 Like

What SO and version of LibO?

Version: 7.2.5.2 (x64) / LibreOffice Community
What does SO stand for?

The document must be fully opened before accessing the Sheets property.

Related question with answers:

1 Like

Thanks a lot :pray: I at least got rid of the error messages by using JohnSUN’s idea to disable the error handler. Would it be possible to load the calc document before the UDF’s so as that the error does not even occur? :thinking:

No. I can only repeat again:

it can be useful
in some situations

1 Like

That’s quite unfortunate, but thanks for the help :slight_smile:

Not everything is so sad. You can in a special way make the function by @JohnSUN volatile:

Function SheetName(Optional nSheet, Optional Dummy) As String
  Dim oSheets
  If IsMissing(nSheet) Then nsheet=Empty
  SheetName = ""
  On Error GoTo ErrLabel
  oSheets = ThisComponent.getSheets()
  If IsEmpty(nSheet) Or nSheet="" Or nSheet=0 Then
    SheetName = ThisComponent.getCurrentController().getActiveSheet().getName()
  Else
    SheetName = oSheets.getByIndex(nSheet - 1).getName()
  End If
  Exit Function

ErrLabel:
End Function

Examples of getting the name of the active sheet and the 3rd sheet of the document:

=SHEETNAME(;TODAY())
=SHEETNAME(3;TODAY())

The Today() function does not affect the result of the calculation, but provides Volatile.
Try opening/closing the document, adding, deleting and renaming sheets.

1 Like