classinstancelibreoffice-calclibreoffice-basic

Libre Calc - Instantiate a class from outside the current library


I am trying to instantiate a class. Within my library ClassLib, it is working ok. But if I try to create an instance of it outside of this library ie. Standard lib. It produces the error.

Object not accessible.
Invalid object reference.

I am using operating system Windows 10. Libre Calc 7.4.7.2.

REM TestClass ------------------------------------------------------------

Option Compatible
Option ClassModule

sub Main
end sub

Private Sub Class_Initialize()
End Sub ' Constructor
Private Sub Class_Terminate()
End Sub ' Destructor

sub testing( s as string )
        msgbox(s)
end sub


REM  Module1 ( ClassLib ) ---------------------------------------------

Sub Main
End Sub

sub test1

        Dim a As Object
        set a = New TestClass
        a.testing(" From Module1 in the ClassLib")

end sub


REM  Test_classInstance -  module in the Standard library ( document ) ------------------

Sub Main
End Sub

sub Test_class_problem 

' this works 

        test1

' Produces the Error - ( See Image link below )

        'Dim b As Object
        'Set b = New ClassLib.TestClass  

' this is produces the same error

        Dim a As Object
        Globalscope.BasicLibraries.LoadLibrary("ClassLib")
        set a = New TestClass
        a.testing("From 'Test_classInstance' in the Standard lib")

end sub

Image showing the Error Message and libraries


Solution

  • Instead of adding the ClassLib. qualifier, load the library (if it hasn't been loaded yet — apparently for example, editing the module will also load it).

    Sub TestTheClass
        Dim a As Object
        Globalscope.BasicLibraries.LoadLibrary("ClassLib")
        set a = New TestClass
        a.testing("From Module 'VBASupp' in the Standard lib")
    End Sub
    

    successful message box

    EDIT:

    If you want to instantiate the class from a module in a document, then it looks like that way won't work. Instead, we can follow the approach that Access2Base takes, which is to create a subroutine in that library that returns a new instance of the class.

    To do this in your example, create a new module ClassLib.App with the following code:

    Function NewTestClass
        NewTestClass = New TestClass
    End Function
    

    Now, to create a new object from a subroutine in a document, do this:

    Globalscope.BasicLibraries.LoadLibrary("ClassLib")
    Set a = NewTestClass
    a.testing("From 'Test_classInstance' embedded in a document")