In a macro, a named range is accessed, created, and deleted using the NamedRanges
property of a Calc document. Use the methods hasByName(name) and
getByName(name) to verify and retrieve a named range. The method
getElementNames() returns an array containing the names of all named ranges. The
NamedRanges object supports the method addNewByname, which accepts four
arguments; the name, content, position, and type. The macro in Listing 10 creates a
named range, if it does not exist, that references a range of cells.
Listing 10. Create a named range that references $Sheet1.$B$3:$D$6.
Sub AddNamedRange()
Dim oRange ' The created range.
Dim oRanges ' All named ranges.
Dim sName$ ' Name of the named range to create.
Dim oCell ' Cell object.
Dim s$
sName$ = "MyNRange"
oRanges = ThisComponent.NamedRanges
If NOT oRanges.hasByName(sName$) Then
REM Obtain the cell address by obtaining the cell
REM and then extracting the address from the cell.
Dim oCellAddress As new com.sun.star.table.CellAddress
oCellAddress.Sheet = 0 'The first sheet.
oCellAddress.Column = 1 'Column B.
oCellAddress.Row = 2 'Row 3.
REM The first argument is the range name.
REM The second argument is the formula or expression to use.
REM The second argument is usually a string that
REM defines a range.
REM The third argument specifies the base address for
REM relative cell references.
REM The fourth argument is a set of flags that define
REM how the range is used, but most ranges use 0.
REM The fourth argument uses values from the
REM NamedRangeFlag constants (see Table 13).
s$ = "$Sheet1.$B$3:$D$6"
oRanges.addNewByName(sName$, s$, oCellAddress, 0)
End If
REM Get a range using the created named range.
oRange = ThisComponent.NamedRanges.getByName(sName$)
REM Print the string contained in cell $Sheet1.$B$3
oCell = oRange.getReferredCells().getCellByPosition(0,0)
Print oCell.getString()
End Sub
316 OpenOffice.org 3.3 Calc Guide
Komentáře k této Příručce