如何在 libre office basic 中使用模块?

问题描述

我习惯了 VBA,但我应该调试一些 libre office 基本代码,所以我尝试在代码隐藏中编写一个基本模块来处理我的工作表。

问题是,每当我尝试运行该模块时,它似乎都不知道起点在哪里等,当我在 excel vba 中启动此代码时,它很容易运行.. 也许有人知道如何在 libre office 中处理模块以及为什么有一个 main 方法..

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

Sub Main
    test()
End Sub


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

解决方法

这里的模块不承载任何功能负载 - 这只是为了方便将项目的过程和功能划分为逻辑相关的代码组。

您的代码无法工作,因为此 Basic 不知道 Worksheets,它使用 ThisComponent.GetSheets() 方法获取当前电子表格的所有工作表。这里集合的元素从 0 开始编号,而不是从 1 开始,就像您在 VBA 中习惯的那样(这也适用于书的页数,以及行数和列数):

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