LibreOffice 宏总是显示#NULL!重新打开文件后

LibreOffice Macro always show #NULL! after reopening the file

我在 LibreOffice Calc 中写了一个宏,它能够 运行 正确。但是如果我关闭文件并重新打开,它总是显示 #NULL! 而不是正确的值。我在这里错过了什么?

我的宏代码

Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Function Calculate(CalType As String) As Double
'
' Calculate Macro
'

Dim i As Integer
Calc = 0

i = 1

Do While Not IsEmpty(Cells(i, 2))
    If (Cells(i, 3).Value = CalType And (Cells(i,2) = "A" Or Cells(i,2) = "B")) Then
        Calculate = Calculate + Cells(i, 4).Value
    ElseIf (Cells(i, 3).Value = CalType And Cells(i,2) = "C") Then
        Calculate = Calculate - Cells(i, 4).Value
    End If
    i = i + 1
Loop

'
End Function

调用函数类似于=Calculate(J6)

文件保存为 .ods 格式。

Cells 调用对我来说根本不起作用。它来自 VBA,而不是 LO Basic。但是我不认为这是主要问题。

LibreOffice 希望用户定义的函数很简单,只访问包含公式的单元格。由于调用该函数时电子表格尚未完全加载,因此无法读取其他单元格。

解决方法是忽略错误并等到文档完全加载后再 运行 函数。以下面的代码为例:

Function ReadOtherCell(row, col)
    On Error GoTo ErrorHandler
    oSheet = ThisComponent.CurrentController.ActiveSheet()
    oCell = oSheet.getCellByPosition(row, col)
    ReadOtherCell = "value is '" & oCell.getString() & "'"
    Exit Function
    ErrorHandler:
        Reset
End Function

Sub RecalculateAll
    ' This is for user-defined functions that need to read the spreadsheet.
    ' Assign it to the "View created" event,
    ' because before that, the spreadsheet is not fully loaded.
    ThisComponent.calculateAll
End Sub

在A1中输入foo,在A2中输入=ReadOtherCell(0,0)。到目前为止,这有同样的问题 -- 第一次打开文档时会失败。

现在,转到 Tools -> Customize。在“事件”选项卡中,突出显示 View created。按 Macro... 并找到 RecalculateAll 函数。然后按确定。

现在,当文档关闭并重新打开时,单元格 A2 应显示结果 value is 'foo'

这源自 B. Marcelly 在 http://ooo-forums.apache.org/en/forum/viewtopic.php?f=20&t=73090&sid=f92a89d676058ab597b4b4494833b2a0 的回答。

我遇到了同样的问题。 我注意到在模块中,我有一个空的 Sub Main 擦除后,功能又开始工作了