Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

10 It Electronic Spreadsheet Notes04

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

myCBSEguide

CBSE Class 10 Information Technology


Revision Notes
Electronic Spreadsheet (Advanced)
Macros In SpreadSheet

Relevant Knowledge
A macro is a saved sequence of commands or keystrokes that are stored for later use. An example of a simple
macro is one that “types” your address. The OpenOffice.org (OOo) macro language is very flexible, allowing
automation of both simple and complex tasks. Macros are especially useful to repeat a task the same way over
and over again.

Using the macro recorder


This session provides a basis for understanding the general macro capabilities in OpenOffice.org using the
macro recorder. The following steps create a macro that performs paste special with multiply.

1. Open a new spreadsheet.


2. Enter numbers into a sheet.

3. Select cell A3, which contains the number 3, and copy the value to the clipboard.
4. Select the range A1:C3.
5. Use Tools > Macros > Record Macro to start the macro recorder. The Record Macro dialog is displayed
with a stop recording button.

6. Use Edit > Paste Special to open the Paste Special dialog.

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 1/8


myCBSEguide

7. Set the operation to Multiply and click OK. The cells are now multiplied by 3.

8. Click Stop Recording to stop the macro recorder. The OpenOffice.org Basic Macros dialog opens.
9. Select the current worksheet. For this example, the current Calc worksheet is Untitled 1. Existing
worksheets show a library named Standard. This library is not created until the worksheet is saved, or the
library is needed, so at this point your new worksheet does not contain a library. You can create a new
library to contain the macro, but this is not necessary.

10. Click New Module. If no libraries exist, then the Standard library is automatically created and used. In the
New Module dialog, type a name for the new module or leave the name as Module1.

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 2/8


myCBSEguide

11. Click OK to create a module named Module1. Select the newly created Module1, enter the macro name
PasteMultiply and click Save.

12. The created macro is saved in Module1 of the Standard library in the Untitled 1 worksheet

Using A Macro As A Function


Using the newly created Calc worksheet CalcTestMacros.ods, enter the formula =NumberFive() (see Figure 2.44).
Calc finds the macro and calls it.

Note: Function names are not case sensitive. You can enter =NumberFive() and Calc clearly shows
=NUMBERFIVE().
Save the Calc document, close it, and open it again. Depending on your settings in Tools > Options >
OpenOffice.org > Security > Macro Security, Calc will display one of the warnings shown below. You will need to
click Enable Macros, or Calc will not allow any macros to be run inside the document.

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 3/8


myCBSEguide

If you choose to disable macros, then when the document loads, Calc can no longer find the function.

When a document is created and saved, it automatically contains a library named Standard. The Standard
library is automatically loaded when the document is opened. No other library is automatically loaded.
Calc does not contain a function named NumberFive(), so it checks all opened and visible macro libraries for
the function. Libraries in OpenOffice.org Macros, My Macros, and the Calc document are checked for an
appropriately named function. The NumberFive() function is stored in the AuthorsCalcMacros library, which is
not automatically loaded when the document is opened.
Use Tools > Macros > Organize Macros > OpenOffice.org Basic to open the OpenOffice.org Basic Macros
dialog shown further down the page. Expand CalcTestMacros and find AuthorsCalcMacros. The icon for a
loaded library is a different color from the icon for a library that is not loaded.
Click the expansion symbol (usually a plus or a triangle) next to AuthorsCalcMacros to load the library. The icon
changes color to indicate that the library is now loaded. Click Close to close the dialog.
Unfortunately, the cells containing =NumberFive() are in error. Calc does not recalculate cells in error unless
you edit them or somehow change them. The usual solution is to store macros used as functions in the Standard
library. If the macro is large or if there are many macros, a stub with the desired name is stored in the Standard
library. The stub macro loads the library containing the implementation and then calls the implementation.

1. Use Tools > Macros > Organize Macros > OpenOffice.org Basic to open the OpenOffice.org Basic Macros
dialog. Select the NumberFive macro and click Edit to open the macro for editing.

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 4/8


myCBSEguide

2. Change the name of NumberFive to NumberFive_Implementation (see Listing 3).


Listing 3. Change the name of NumberFive to NumberFive_Implementation
Function NumberFive_Implementation()
NumberFive_Implementation() = 5
End Function
3. In the Basic IDE, hover the mouse cursor over the toolbar buttons to display the tool tips. Click the Select
Macro button to open the OpenOffice.org Basic Macros dialog.
4. Select the Standard library in the CalcTestMacros document and click New to create a new module. Enter a
meaningful name such as CalcFunctions and click OK. OOo automatically creates a macro named Main and
opens the module for editing.
5. Create a macro in the Standard library that calls the implementation function (see Listing 4). The new
macro loads the AuthorsCalcMacros library if it is not already loaded, and then calls the implementation
function.
Listing 4. Change the name of NumberFive to NumberFive_Implementation. Function NumberFive()
If NOT BasicLibraries.isLibraryLoaded("AuthorsCalcMacros") Then
BasicLibraries.LoadLibrary("AuthorsCalcMacros")
End If
NumberFive = NumberFive_Implementation()
End Function
Save, close, and reopen the Calc document. This time, the NumberFive() function works.

Passing Arguments to Macros


To illustrate a function that accepts arguments, we will write a macro that calculates the sum of its arguments
that are positive—it will ignore arguments that are less than zero (see Listing 5).
Listing 5. PositiveSum calculates the sum of the positive arguments.
Function PositiveSum(Optional x)
Dim TheSum As Double
Dim iRow As Integer
Dim iCol As Integer

TheSum = 0.0
If NOT IsMissing(x) Then
If NOT IsArray(x) Then
If x > 0 Then TheSum =x
Else
For iRow = LBound(x, 1) To UBound (x, 1)
For iCol = LBound(x, 2) To UBound (x, 2)
If x(iRow, iCol) > 0 Then TheSum = TheSum + x(iRow, iCol)
Next
Next
End If
End If
PositiveSum = TheSum
End Function
The macro in Listing 5 demonstrates a couple of important techniques.

1. The argument x is optional. If the argument is not optional and it is called without an argument, OOo prints

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 5/8


myCBSEguide

a warning message every time the macro is called. If Calc calls the function many times, then the error is
displayed many times.
2. IsMissing checks that an argument was passed before the argument is used.
3. IsArray checks to see if the argument is a single value, or an array. For example, = PositiveSum(7) or =
PositiveSum(A4). In the first case, the number 7 is passed as an argument, and in the second case, the value
of cell A4 is passed to the function.
4. If a range is passed to the function, it is passed as a two-dimensional array of values; for example,
=PositiveSum(A2:B5). LBound and UBound are used to determine the array bounds that are used. Although
the lower bound is one, it is considered safer to use LBound in case it changes in the future.
Note: The macro in Listing 5 is careful and checks to see if the argument is an array or a single argument.
The macro does not verify that each value is numeric. You may be as careful as you desire. The more things
you check, the more robust the macro is, and the slower it runs. Passing one argument is as easy as passing
two: add another argument to the function definition (see Listing 6). When calling a function with two
arguments, separate the arguments with a semicolon; for example, =TestMax(3; -4).

Listing 6. TestMax accepts two arguments and returns the larger of the two.
Function TestMax }(x, y)
If x >= y Then
TestMax = x
Else
TestMax = y
End If
End Function

Passing Arguments as Values


Arguments passed to a macro from Calc are always values. It is not possible to know what cells, if any, are used.
For example, =PositiveSum(A3) passes the value of cell A3, and PositiveSum has no way of knowing that cell A3
was used. If you must know which cells are referenced rather than the values in the cells, pass the range as a
string, parse the string, and obtain the values in the referenced cells.

Writing Macros that act like built-in Functions


Although Calc finds and calls macros as normal functions, they do not really behave as built-in functions. For
example, macros do not appear in the function lists. It is possible to write functions that behave as regular
functions by writing an Add-In.

Accessing Cells Directly


You can access the OOo internal objects directly to manipulate a Calc document. For example, the macro in
Listing 7 adds the values in cell A2 from every sheet in the current document. This Component is set by
StarBasic when the macro starts to reference the current document. A Calc document contains sheets:
ThisComponent.getSheets(). Use getCellByPosition(col, row) to return a cell at a specific row and column.
Listing 7. Add cell A2 in every sheet.
Function SumCellsAllSheets()
Dim TheSum As Double
Dim i As integer
Dim oSheets
Dim oSheet
Dim oCell
oSheets = ThisComponent.getSheets()

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 6/8


myCBSEguide

For i = 0 To oSheets.getCount() - 1
oSheet = oSheets.getByIndex(i)
oCell = oSheet.getCellByPosition (0, 1) ' GetCell A2
TheSum = TheSum + oCell.getValue()
Next
SumCellsAllSheets = TheSum
End Function

Sorting
Sorting data can be automated in Open Office by creating a Macro in Calc. Data can be sorted on a single
column or more than one column. Each time the Macro runs the data gets sorted. Such macros can be written
using code in Open Office. Consider sorting the data in the figure below. First, sort on column B descending and
then column A ascending.

The example in Listing 9, however, demonstrates how to sort on two columns.


Listing 9. Sort cells A1:C5 on Sheet 1.
Sub SortRange
Dim oSheet 'Calc sheet containing data to sort.
Dim oCellRange 'Data range to sort.

REM An array of sort fields determines the columns that are


REM sorted. This is an array with two elements, 0 and 1.
REM To sort on only one column, use:
REM Dim oSortFields(0) As New com.sun.star.util.SortField
Dim oSortFields(1) As New com.sun.star.util.SortField

REM The sort descriptor is an array of properties.


REM The primary property contains the sort fields.
Dim oSortDesc(0) As New com.sun.star.beans.PropertyValue

REM Get the sheet named "Sheet1"


oSheet = ThisComponent.Sheets.getByName("Sheet1")

REM Get the cell range to sort


oCellRange = oSheet.getCellRangeByName("A1:C5")

REM Select the range to sort.


REM The only purpose would be to emphasize the sorted data.
'ThisComponent.getCurrentController.select(oCellRange)

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 7/8


myCBSEguide

REM The columns are numbered starting with 0, so


REM column A is 0, column B is 1, etc.
REM Sort column B (column 1) descending.
oSortFields(0).Field = 1
oSortFields(0).SortAscending = FALSE

REM If column B has two cells with the same value,


REM then use column A ascending to decide the order.
oSortFields(1).Field = 0
oSortFields(1).SortAscending = True

REM Setup the sort descriptor.


oSortDesc(0).Name = "SortFields"
oSortDesc(0).Value = oSortFields()

REM Sort the range.


oCellRange.Sort(oSortDesc())
End Sub

Copyright © myCBSEguide.com. Mass distribution in any mode is strictly prohibited. 8/8

You might also like