LibreOffice Calc Range Max 和删除宏

问题描述

我在 libreoffice Calc 中有一个工作表,它有一个 Id 列,增量值从 1 到 N。

ID column

我需要在 VBA 中创建一个宏(链接到我稍后将创建的按钮),我可以在其中选择最后一个 ID(也是 MAX ID)并删除与此 ID 相关的整行。

到目前为止我已经尝试过了

Sub suppression

dim maxId as Integer

my_range = ThisComponent.Sheets(0).getCellRangebyName("B19:B1048576")

maxId = Application.WorksheetFunction.Max(range("Dépôts!B19:B1048576"))
MsgBox maxId

End Sub

非常感谢您的帮助。

解决方法

在 libreoffice BASIC 中,您首先需要获取单元格范围的数据数组。这是一个数组数组,每个数组代表单元格范围的一行。无论单元格范围在工作表中的位置如何,它都是从零开始索引的。因为您的单元格范围是一列宽,所以每个成员数组只有一个成员,索引为零。

正如 Jim K 所说,“Application.WorksheetFunction”来自 VBA。可以在 LibreOffice BASIC 中使用工作表函数,但这些函数作用于普通数组而不是元胞数组,并且 MAX 函数采用一维数组,因此有必要首先使用循环重塑数据数组。此外,如果您想删除对应于最大值的行,那么您将面临仅使用值本身来查找该行的索引的问题。

通过循环遍历数据数组来查找索引要简单得多,如下面的代码片段所示。

此外,通过 LibreOffice 提供的 BASIC 函数“GetLastUsedRow(oSheet as Object)”获取电子表格最后使用的行,而不是遍历超过一百万行,从而节省计算工作。它位于“LibreOffice 宏和对话框”中的“工具”库中。要使用它,您必须在调用该函数之前将语句: 'Globalscope.BasicLibraries.LoadLibrary("Tools")' 放在某处。

要删除已识别的行,请获取电子表格的 XTableRows 接口并调用其 removeByIndex() 函数。

以下代码段假设表格的标题行位于工作表的第 18 行,如示例代码所建议的那样,从零开始编号时位于第 17 行。

Sub suppression()

' Specify the position of the index range
''''''''''''''''''''''''''''''''''''
Dim nIndexColumn As Long           '
nIndexColumn = 1                   '
                                   '
Dim nHeaderRow As Long             '
nHeaderRow = 17                    '
                                   ' 
'''''''''''''''''''''''''''''''''''' 

Dim oSheet as Object
oSheet = ThisComponent.getSheets().getByIndex(0)

' Instead of .getCellRangebyName("B19:B1048576") use: 

Globalscope.BasicLibraries.LoadLibrary("Tools")
Dim nLastUsedRow As Long
nLastUsedRow = GetLastUsedRow(oSheet)

Dim oCellRange As Object
'                                             Left           Top         Right         Bottom 
oCellRange = oSheet.getCellRangeByPosition(nIndexColumn,nHeaderRow,nIndexColumn,nLastUsedRow)

' getDataArray() returns an array of arrays,each repressenting a row.
' It is indexed from zero,irrespective of where oCellRange is located
' in the sheet
Dim data() as Variant
data = oCellRange.getDataArray()

Dim max as Double
max = data(1)(0)

' First ID number is in row 1 (row 0 contains the header).
Dim rowOfMaxInArray As Long
rowOfMaxInArray = 1

Dim i As Long,x As Double
For i = 2 To UBound(data)
    x =  data(i)(0)
    If  x > max Then
        max = x
        rowOfMaxInArray = i
    End If
Next i

' if nHeaderRow = 0,i.e. the first row in the sheet,you could save a
' couple of lines by leaving the next statement out
Dim rowOfMaxInSheet As long
rowOfMaxInSheet = rowOfMaxInArray + nHeaderRow

oSheet.getRows().removeByIndex(rowOfMaxInSheet,1)

End Sub