如何在不修改电子表格的情况下 return 修改范围

How to return a modified range without modify the spreadsheet

我希望我的 VLOOKUP_RANGE() 使用 ByVal VBA Range 'search' 到 return 一个修改过的 Range 对象,像 =SUMPRODUCT(VLOOKUP_RANGE(H2:I2;A2:B11;2);H3:I3) 但是 sheet 也被修改了(键被值替换)。

我的猜测是一个范围只包含坐标和一个 sheet 键。

是否可以像我的示例一样使用函数,也许使用另一种对象类型?

Option VBASupport 1
Option Compatible

Function VLOOKUP_RANGE(ByVal range_to_modify, ref_range, index As Integer, Optional sorted As Boolean = False)
    calc_built_in = getProcessServiceManager().createInstance("com.sun.star.sheet.FunctionAccess")
    sheet = ThisComponent.getCurrentController.ActiveSheet
    'VBA Range to LibreOffice
    lo_ref_range = sheet.getCellRangebyName(ref_range.Address)
    
    Dim sum
    For Each cell In range_to_modify
        If cell.Value <> 0 Then
            cell.Value = calc_built_in.callFunction("VLOOKUP", Array(cell.Value, lo_ref_range, index, sorted))
        End If
    Next
    
    VLOOKUP_RANGE = range_to_modify
End Function

在LibreOffice中可以这样写函数,比如这样:

Option Explicit 

Function VLOOKUP_RANGE(range_to_modify As Variant, ref_range As Variant, index As Integer) As Variant 
Dim i As Long, j As Long, m As Long

    If index < LBound(ref_range,2) Or index > UBound(ref_range,2) Then Exit Function 

    For i = LBound(range_to_modify,1) To UBound(range_to_modify,1)
        For j = LBound(range_to_modify,2) To UBound(range_to_modify,2)
            For m = LBound(ref_range,1) To UBound(ref_range,1)
                If range_to_modify(i, j) = ref_range(m, 1) Then
                    range_to_modify(i, j) = ref_range(m, index)
                    Exit For 
                EndIf 
            Next m
        Next j
    Next i
    VLOOKUP_RANGE = range_to_modify
End Function

但是,最好使用由 Calc 的 built-in 函数组成的公式,如评论中所建议的那样。