(In addition to what @igorlius altready posted:)
The CurrentSelection of a spreadsheet document is’nt always an object of the same type (supporting the same services). If nothing explicitly is selected, the cell having the keyboard focus is returned. You also get a single cell returned if one cell is selected (shown highlighted). The focus isn’t evaluated now. In both these cases the service com.sun.star.sheet.SheetCellRange
is also supported by the selection, and the code suggested by @igorlius can work with only the value 0
for i
and for j
as well. If a single range of more than one cell is selected: No problem, that’s the standard case.
If more than one single range is selected, the mentioned service will not be supported. The relevant service you need to rely on now is com.sun.star.sheet.SheetCellRanges
(Regard the plural-s.)
If you want code also working with such a selection, you can use:
Sub loopThroughSingleCellsOfTheCurrentSelection()
REM The CurrentSelection will even contain the stacked ranges
REM of additional sheets IF MORE THAN ONE SHEET IS SELECTED.
sel =ThisComponent.CurrentSelection
If sel.supportsService("com.sun.star.sheet.SheetCellRanges") Then
rgs = sel
Else
If NOT sel.supportsService("com.sun.star.sheet.SheetCellRange") Then Exit Sub
rgs = ThisComponent.createInstance("com.sun.star.sheet.SheetCellRanges")
rgs.addRangeAddress(sel.RangeAddress, False)
End If
For Each rg In rgs
uR = rg.Rows.Count - 1
uC = rg.Columns.Count - 1
For r = 0 To uR
For c = 0 To uC
rcCell = rg.getCellByPosition(c, r)
REM Do here whatever you want to do with the single cell. Example:
Print rcCell.AbsoluteName
Next c
Next r
Next rg
End Sub