Function accessing cell range

前端 未结 2 973
Happy的楠姐
Happy的楠姐 2021-01-13 09:31

I don\'t find how to use cell ranges with functions.

I vainly searched some examples.

I wrote the following test. I get \"Object variable not set\" error o

相关标签:
2条回答
  • 2021-01-13 10:04

    With Calc spreadsheets it is not possible to hand over CellRange objects as parameters to User Defined Functions. If you give a cell range as the parameter, then this will be always a variant array. So there are two possibilities.

    Either you need the cell values in the function, then you can take the variant array and use it:

    public function CHECKBZRANGE(vCellRangeValues as variant) as integer
    
        dim i as integer
        dim vCellValue as variant
    
        if not isarray(vCellRangeValues) then
            vCellValue = vCellRangeValues
            msgbox vCellValue
            i = i + 1
            CHECKBZRANGE = i
            exit function
        end if
    
        for each vCellValue in vCellRangeValues
            msgbox vCellValue
            i = i + 1
        next
    
        CHECKBZRANGE = i
    end function
    

    Can be used as: =CHECKBZRANGE(A6:C9)

    Or you need really the cell range object, then you must give its positions as parameters:

    public function CHECKBZRANGE2(lcol1 as long, lrow1 as long, lcol2 as long, lrow2 as long ) as integer
    
        dim i as integer
        dim oCellRange as object
        dim lRow as long
        dim lCol as long
        dim oCell as object
    
        oCellRange = ThisComponent.CurrentController.ActiveSheet.getCellRangeByPosition(lcol1-1,lrow1-1,lcol2-1,lrow2-1)
    
        for lCol = 0 to oCellRange.Columns.Count -1
         for lRow = 0 to oCellRange.Rows.Count -1
            oCell = oCellRange.getCellByPosition(lCol, lRow)
            msgbox oCell.AbsoluteName
            i = i + 1
         next
        next
    
        CHECKBZRANGE2 = i
    end function
    

    Can be used as: =CHECKBZRANGE2(COLUMN(A6);ROW(A6);COLUMN(C9);ROW(C9))

    Hint: This will only be recalculated if either A6 or C9 has changed.

    0 讨论(0)
  • 2021-01-13 10:16

    Yes. It is possible! Just activating compatibility to VBA.

    Option VBASupport 1
    
    Option Compatible
    
    Function Addressing(R As Range)
    
    Addressing = R.Address
    
    End Function
    
    0 讨论(0)
提交回复
热议问题