LibreOffice Macro always show #NULL! after reopening the file

混江龙づ霸主 提交于 2019-12-02 17:02:21

问题


I wrote a macro in LibreOffice Calc and it is able to run correctly. But if I close the file and reopen, it always show #NULL! instead of the correct value. What am I missing here?

My macro code

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

The calling function will be something like =Calculate(J6)

The file is saved as .ods format.


回答1:


The Cells call did not work at all for me. It is from VBA, not LO Basic. However I do not think that is the main problem.

LibreOffice expects that user-defined functions will be simple, only accessing the cell that contains the formula. Since the spreadsheet has not been fully loaded yet when the function is called, it is not possible to read other cells.

The workaround is to ignore errors and wait until the document is fully loaded before running the function. Take the following code as an example:

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

Enter foo in A1, and =ReadOtherCell(0,0) in A2. So far, this has the same problem -- It will fail when the document is first opened.

Now, go to Tools -> Customize. In the Events tab, highlight View created. Press Macro... and find the RecalculateAll function. Then press OK.

Now when the document is closed and reopened, cell A2 should show the result value is 'foo'.

This is derived from B. Marcelly's answer at http://ooo-forums.apache.org/en/forum/viewtopic.php?f=20&t=73090&sid=f92a89d676058ab597b4b4494833b2a0.




回答2:


I had the same problem. I noticed that in the module, i had an empty Sub Main After i 've erased it, the functions started working again



来源:https://stackoverflow.com/questions/39227757/libreoffice-macro-always-show-null-after-reopening-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!