Search code examples
excelvbalibreofficeworksheet-functionbasic

How to use a module in libre office basic?


I'm used to VBA, but I am supposed to debug some libre office basic code, so I tried to write a basic module in the code-behind to address my worksheet.

The thing is, that whenever I try to run the module it seems, that it doesn't know where the starting point is etc., when I start this code in excel vba, it runs easily.. Maybe someone knows how to handle modules in libre office and why there is a main method..

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

Sub Main
    Test()
End Sub


Sub Test    
    Dim MyStringVariable As String
    MyStringVariable = "Wow!"
    Worksheets(1).Range("A1").Value = MyStringVariable
End Sub

Solution

  • Here the modules do not carry any functional load - this is only for the convenience of dividing the procedures and functions of your project into logically related code groups.

    Your code cannot work because this Basic does not know Worksheets, it gets all sheets of the current spreadsheet using the ThisComponent.GetSheets() method. The elements of collections here are numbered from 0, not from 1, as you are used to in the VBA (this also applies to the sheets of the book, and the numbers of rows and columns):

    REM  *****  BASIC  *****
    
    Sub Main
    ' This is just "template" - you can leave it empty, or remove it, or fill with code '
    End Sub
    
    Sub Test    
        Dim MyStringVariable As String
        MyStringVariable = "Wow!"
        ThisComponent.GetSheets().getByIndex(0).getCellRangeByName("A1").setString(MyStringVariable)
    ' Better write this as '
    Dim oSheets As Variant
    Dim oSheet As Variant
    Dim oCell As Variant
        oSheets = ThisComponent.getSheets()
        oSheet = oSheets.getByIndex(0)
        oCell = oSheet.getCellByPosition(0, 0)
        oCell.setString(MyStringVariable)
    End Sub