问题
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 on both "for" lines (one is without "RangeAddress", and the second is with it, because I'm not sure of the correct syntax):
function CHECKBZRANGE(cellRange) as integer
dim nCol as integer
dim nLine as integer
dim i as integer
for nCol = cellRange.StartColumn to cellRange.EndColumn
for nLine = cellRange.RangeAddress.StartRow to cellRange.RangeAddress.EndRow
i = i + 1 ' placeholder for some computation
next nLine
next nCol
checkBZ_range = i
end function
This function is called with a cell like =CHECKBZRANGE(A6:C9)
Can someone explain how to use a cell range passed by argument ?
回答1:
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.
来源:https://stackoverflow.com/questions/33059048/function-accessing-cell-range