Porting Excel/Vba To Calc/Starbasic
Porting Excel/Vba To Calc/Starbasic
Porting Excel/Vba To Calc/Starbasic
Calc/StarBasic
Contents
Contents...........................................................................................................................................ii
Overview........................................................................................................................................iii
Copyright and trademark information.......................................................................................iii
Feedback....................................................................................................................................iii
Acknowledgments......................................................................................................................iv
Modifications and updates ........................................................................................................iv
Introduction......................................................................................................................................1
Terminology................................................................................................................................1
StarBasic Background.................................................................................................................1
Understanding the OpenOffice Object Model............................................................................2
Examples of Porting Visual Basic for Applications to StarBasic....................................................4
General Programming Notes.......................................................................................................4
Application..................................................................................................................................5
Workbooks/Workbook................................................................................................................7
Worksheets/Worksheet.............................................................................................................11
Range/Cell.................................................................................................................................14
Charts/Chart..............................................................................................................................19
Controls.....................................................................................................................................22
UserForms.................................................................................................................................24
Integrated Development Environment (IDE) Differences.............................................................33
Porting Sample Workbook [Spreadsheet]......................................................................................35
Porting Tasks.............................................................................................................................35
Run-time Experiences...............................................................................................................39
Appendix A: XRay tool................................................................................................................40
Appendix B: Supporting Functions...............................................................................................44
Appendix C: Multi-Page Control..................................................................................................48
Bibliography..................................................................................................................................53
Public Documentation License, Version 1.0..................................................................................54
Overview
Although OpenOffice 1.1 Calc is able to read Microsoft Excel workbooks, compatibility
extends primarily to functionality found in worksheets. Excel workbooks with Visual Basic
for Applications (VBA) macros embedded do not function in Calc, even though VBA and
StarBasic (SB) are syntactically the same. The reason Excel/VBA workbooks do not work
under Calc/SB is due to the differences in the underlying object models for Excel and Calc.
The intent of this document is to show, by way of examples, how to port VBA macros
accessing Excel objects to the equivalent SB macros accessing Calc objects. This manual is
written from the perspective of an experienced Excel/VBA programmer. Hence the reader is
assumed to know the VBA language and is familiar with the MS Excel Object Model. This
document is not a tutorial on SB.
The information contained here is based on Excel 2000 and OpenOffice 1.1 object models.
A discussion covering all aspects of the Excel object model is beyond the scope of this
manual. This manual's intent is to provide sufficient examples where the reader can get
started in porting VBA to SB and to point the reader to other references for more complete
information.
This manual is a living document and is expected to be updated as more experience is gained.
The reader should feel free to contact the author to suggest areas to expand this document.
Feedback
Please direct any comments or suggestions about this document to:
dev@documentation.openoffice.org and masato12610@openoffice.org
Acknowledgments
First, thank you to all the folks posting and responding on the various mailing lists and
forums. These exchanges formed the basis for several examples found in this manual.
Second, I'd like to thank the following individuals who took time out of their busy schedule
to suggest changes to improve the document's readability and the code efficiency: dfrench,
Geoff Farrell, Ian Laurenson, Andrew Pitonyak and Juergen Schmidt. Lastly, I'd like to
express my sincerest thank you to my wife, Nora, for her patience and allowing me the time
to work on this manual.
Introduction
This chapter introduces the core concepts that provide a basis for the discussion that follows
in the rest of this document.
After establishing some core concepts, the document is composed of chapters that cover the
following topics:
• Examples that compare Visual Basic for Applications (VBA) code interacting with the
Excel object model to StarBasic (SB) code interacting with the OpenOffice object model.
• Discussion on the differences between the integrated development environments (IDE)
provide with VBA and SB
• Discussion on converting a sample Excel workbook with VBA macros into a Calc
Spreadsheet with SB macros.
Terminology
The terminology used in this document is geared toward Excel/VBA programmers because
they comprise the target audience. The following convention is followed. This manual uses
Excel specific terms, and if there is a different Calc term for the equivalent entity, it follows
the Excel term in square brackets. See the following as illustrative examples:
• workbook [spreadsheet]
• worksheet [sheet]
StarBasic Background
For the Excel/VBA programmer, SB is a Basic programming language very similar to VBA.
The primary reason that VBA does not work in Calc, even though Calc is able to read the
Excel workbook, is that Calc uses a different method to access the workbook [spreadsheet]
components, such as cells on the worksheet [sheet]. The access mechanisms are different in
Calc. Specifically the objects, attributes and methods use different names and the
corresponding behavior is sometimes slightly different.
For those who wish a better understanding of SB, there are several documents publicly
available that explain the language and programming environment. These documents, listed
in the Bibliography, can be found on the Web.
• StarOffice 7 Software Basic Programmer's Guide
• Migrating from Microsoft Office to StarOffice 7
• Useful Macro Information For OpenOffice
• How to Use BASIC Macros in OpenOffice.org
These are excellent resources for those who are getting started in SB macro programming.
Using the method getCellRangeByName() we are able to locate the range "MyMatrix" using
the call .getCellRangeByName("MyMatrix").
From the "Spreadsheet" section of the Developer's Guide, the programmer sees that using the
service com.sun.star.sheet.SheetCellRange, we obtain access to the service
XColumnRowRange. This services provides access to the columns and rows of the range.
From here we see that we can invoke the method getRows() to retrieve the collection of rows
making up the range.
However, at this point it is not clear how to get the number of rows. By remembering the
concept of inheritance, the programmer should realize that "rows" is a specialization of the
class "collection", and according the the object model, "rows" inherits from "collections"
Now looking at the methods associated for collections, the programmer sees in the
com::sun::star::container::XIndexAccess interface a method getCount() that retrieves the
number of items in a collection.
Putting all of this together we now have a way to determine the number of rows in a range of
cells. The SB call looks like
ThisComponent.CurrentController.ActiveSheet.getCellRangeByName("MyMatrix").
getRows.getCount()
The moral of this little tale is that the Excel/VBA programmer, in making the transition to
StarBasic, should remember to consider the concept of inheritance.
The following URL are the main reference material for this manual:
• http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html
• http://api.openoffice.org/docs/common/ref/com/sun/star/module-ix.html
In doing research for this manual, a useful debugging tool was found. The tool is called
XRay, developed by Bernard Marcelly, and can be found at
http://www.ooomacros.org/dev.php101416. XRay allows a programmer to inspect at run-
time the various Calc objects. This is similar in function to the VBA debugger. In
combination with the downloaded OOo SDK, XRay is able to bring up SDK related
documentation for an object while you are using XRay to view Calc objects. This feature is
useful in understanding the Calc object model. Features of XRay are illustrated in Appendix
A.
oSheet = ThisComponent.CurrentController.ActiveSheet
'or
Application
Object representing the workbook [spreadsheet] that is active
VBA ActiveWorkbook
SB ThisComponent
Reference:
http://api.openoffice.org/docs/DevelopersGuide/ProfUNO/ProfUNO.htm#1+Professional+UNO
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+3+2+2+ThisC
omponent
Object representing the worksheet [sheet] in the workbook [spreadsheet] that is active
VBA ActiveSheet
SB ThisComponent.CurrentController.ActiveSheet
Reference :
http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.htm#1+Office+Development
http://api.openoffice.org/docs/common/ref/com/sun/star/sheet/XSpreadsheetView.html#getActiveSheet
oSheet = ThisComponent.CurrentController.ActiveSheet
msgbox FuncService.callFunction("AVERAGE", _
array(oSheet.getCellRangeByName("A1:A5")))
msgbox FuncAcc.CallFunction("MAX", _
array(oSheet.getCellRangeByName("A1:A5"), _
oSheet.getCellRangeByName("C1:C5")))
End Sub
Usage Note: Two arguments are needed for callFunction() method. The first is a
string containing the name of the worksheet [sheet] function to invoke. The second is
an array containing the arguments to that function.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/Spreadsheet/Spreadsheet.htm#1+4+2+1+Calculating+Fu
nction+Results and http://api.openoffice.org/docs/common/ref/com/sun/star/sheet/XFunctionAccess.html
Workbooks/Workbook
List names all open workbooks [spreadsheets]
VBA Sub MyProc
Dim wbk as Workbook
Usage Note: The oDoc.nextElement() call returns all opened OO.o documents
including Writer documents. So the potential exists to return more than just open Calc
documents.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+3+2+1+StarD
esktop,
Open workbook "My2ndWorkbook" that is located in the same directory as the currently
active workbook.
VBA Sub MyProc
Dim NewWorkbook as Workbook
SB Sub MyProc
Dim DirectoryName as String
Dim NewWorkbook as Object
Dim NoArgs() 'empty array for no arguments
NewWorkbook = StarDesktop.loadComponentFromURL _
("file:///" & DirectoryName & "/My2ndWorkbook.sxc", _
"_blank",0 ,NoArgs() )
End Sub
Usage Note: See example for obtaining directory of currently active workbook
[spreadsheet] later on in this manual. For both Excel and Calc, if there is a macro to be
executed when the workbook [spreadsheet] is opened, the macro will not be executed
using the above code fragment. Regarding the specific SB code show above, another
side-effect is that no macro associated with any event, such as "When Initiating" for
controls, will execute. If it is desired to execute the macros based on events occurring
in the workbook [spreadsheet], see the next example.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.htm#1+1+5+1+Loading+Documen
ts and
http://api.openoffice.org/docs/common/ref/com/sun/star/frame/XComponentLoader.html#loadComponen
tFromURL
Open workbook "My2ndWorkbook" that is located in the same directory as the currently
active workbook and execute the macro associated with the opening of the workbook
[spreadsheet].
VBA Sub MyProc
Dim NewWorkbook as Workbook
Args(0).Name = "MacroExecutionMode"
Args(0).Value = _
com.sun.star.document.MacroExecMode.ALWAYS_EXECUTE
NewWorkbook = StarDesktop.loadComponentFromURL _
("file:///" & DirectoryName & "/My2ndWorkbook.sxc", _
"_blank",0 ,Args() )
End Sub
Usage Note: This enables the macro associated with the "Open Document" event to
execute when the spreadsheet is opened. In addition, other macros associated with
other events, such as "When Initiating" event for controls, will function as well.
Reference: http://api.openoffice.org/servlets/ReadMsg?list=dev&msgNo=10707 ,
http://api.openoffice.org/docs/common/ref/com/sun/star/document/MediaDescriptor.html and
http://api.openoffice.org/docs/common/ref/com/sun/star/beans/PropertyValue.html
End Sub
Usage Note: Format of URL, at least for file based documents are
"file:///<directory>/<filename>".
End Sub
Usage Note: Format of URL, at least for file based documents are
"file:///<directory>/<filename>". Use the method ConvertFromURL() to convert from
URL notation to the standard notation.
Worksheets/Worksheet
Add a new worksheet [sheet] named "MyNewSheet" to the current workbook
VBA Sub MyProc
Dim wksh as Worksheet
Sub MyProc
Dim oSheeet as object
Dim oSheets
oSheets = ThisComponent.Sheets
Usage Note: For purposes of illustration in this manual, no error checking is done for
the return value of findSheetIndex(). In the event the worksheet [sheet] is not found,
-1 is returned by the function.
Delete worksheet [sheet] named "MyNewSheet" from the current workbook [spreadsheet]
VBA Worksheets("MyNewSheet").Delete
SB ThisComponent.Sheets.removeByName("MyNewSheet")
Reference:
http://api.openoffice.org/docs/DevelopersGuide/ProfUNO/ProfUNO.htm#1+3+5+Collections+and+Conta
iners and
http://api.openoffice.org/docs/common/ref/com/sun/star/container/XNameContainer.html#removeByNa
me
VBA In Excel, predefined procedures exist the events of activating and deactivating
worksheets. For each worksheet, add code to the predefined procedures. The
procedure stubs are shown below.
End Sub
End Sub
'create listner
oActiveSheetListener = createUnoListener("ACTIVESHEET_", _
"com.sun.star.beans.XPropertyChangeListener")
End Sub
case "Sheet2"
'do Sheet2 specific deactivate processing
end select
case "Sheet2"
'Do Sheet2 specific activate processing
end select
oSheet = ThisComponent.Sheets.getByName("MySheet")
ThisComponent.CurrentController.setActiveSheet(oSheet)
End Sub
Range/Cell
Storing a number into a cell.
VBA Range("B1").Value = 12
SB ThisComponent.CurrentController.ActiveSheet.getCellRangeByName
("B1").Value = 12
Reference:
http://api.openoffice.org/docs/DevelopersGuide/Spreadsheet/Spreadsheet.htm#1+3+1+5+Cells and
http://api.openoffice.org/docs/common/ref/com/sun/star/table/XCell.html
Acccess the cell F2 in the Range("B1:E5") by relative position. (Note: Cell F2 is out of
the Range("B1:E5"))
VBA Range("B1:E5").Cells(2,5).Value
Range("B1:E5").Offset(1,4).Value
SB Not possible in SB
Usage Note: If the same SB technique is used as in the previous example of accessing
cell C4, the execution of the macro program will be interrupted with an
com.sun.star.lang.IndexOutOfBoundException. VBA does not enforce any bounds
checking on the row and column indices for the cell range. If accessing a cell outside
the specified range is a requirement for a SB macro program, the only solution is to
calculate the absolute cell locations on the worksheet [sheet].
Sub MyProc
Dim oSheet as Object
oSheet = ThisComponent.CurrentController.ActiveSheet
End Sub
Usage Note: After some time spent researching and experimentation, the approach of
using the Calc sheet function "ADDRESS()" was selected. It may be possible that a
method or property exists in the UNO object model to obtain a string representation of
the address of a cell or range of cells but it is not clear as of this writing.
Find the cell at the end of a row or column of data in a worksheet [sheet]. Assume all the
cells in range B3:E15 contains data. This does not depend on knowing the actual number
of rows or columns in the data range.
VBA Sub MyProc
'go to upper left corner of range
Range("B3").Select
End Sub
Sub MyProc
Dim oSheet as Object, oCell as Object
End Sub
Clear the contents in the range of cells on the ActiveSheet. This does not affect any
formatting of the cells.
VBA Range("B1:E5").ClearContents
SB ThisComponent.CurrentController.ActiveSheet.getCellByName
("B1:E5").clearContents( _
com.sun.star.sheet.CellFlags.VALUE _
+com.sun.star.sheet.CellFlags.STRING _
+com.sun.star.sheet.CellFlags.DATETIME)
Reference:
http://api.openoffice.org/docs/DevelopersGuide/Spreadsheet/Spreadsheet.htm#1+3+1+4+8+Operations,
http://api.openoffice.org/docs/common/ref/com/sun/star/sheet/XSheetOperation.html#clearContents and
http://api.openoffice.org/docs/common/ref/com/sun/star/sheet/CellFlags.html
Clear a range of cells on the worksheet [sheet] "MySheet". This clears everything
associated with the cell including formatting.
VBA Worksheets("MySheet").Range("B1:E5").Clear
SB ThisComponent.Sheets.getByName("MySheet").getCellRangeByName
("B1:E5").clearContents( _
com.sun.star.sheet.CellFlags.VALUE _
+ com.sun.star.sheet.CellFlags.STRING _
+ com.sun.star.sheet.CellFlags.DATETIME _
+ com.sun.star.sheet.CellFlags.ANNOTATION _
+ com.sun.star.sheet.CellFlags.FORMULA _
+ com.sun.star.sheet.CellFlags.HARDATTR _
+ com.sun.star.sheet.CellFlags.STYLES _
+ com.sun.star.sheet.CellFlags.OBJECTS _
+ com.sun.star.sheet.CellFlags.EDITATTR)
Assign a user defined name "MyCells" to the cells B2:C3 via the Excel [Calc] user
interface
Excel One of two methods:
1) Highlight cells B2:C3, select the tool bar options: Insert > Name > Define ,
enter name "MyCells" in pop-up window and press "Add" button.
2) Highlight cells B2:C3, then enter "MyCells" in the Name Field on the
active window.
Calc One of two methods:
1) Highlight cells B2:C3, select the tool bar options: Insert > Names >
Define, enter name "MyCells" in pop-up window and press "Add" button.
2) Highlight cells B2:C3, press Ctrl-F3, enter name "MyCells" in pop-up
window and press "Add" button.
Assign a user defined name "MyCells" to the cells B2:C3 on "Sheet1" and the same name
to cells A1:B3 on "Sheet2" via the Excel [Calc] user interface
Excel Select "Sheet1" and highlight cells B2:C3 then do one of the following:
1) Select the tool bar options: Insert > Name > Define , enter name
"Sheet1!MyCells" in pop-up window and press "Add" button.
2) Enter "Sheet1!MyCells" in the Name Field on the active window.
Select "Sheet2" and highlight cells A1:B3 then repeat either steps 1 or 2 from
above only this time use the name "Sheet2!MyCells".
Calc It is not possible. Calc appears not to allow the same range name, e.g.
"MyCells", to exist on two or more worksheets [sheets].
Access ranges with the same name relative to worksheets [sheets]. Assume in worksheet
[sheet] "Sheet1" cell B1 is named "MyCell" and contains the string "Sheet1MyCell". In
worksheet [sheet] "Sheet2" cell C3 is named "MyCell" and contains the string
"Sheet2MyCell".
VBA Rem The following will display "Sheet1MyCell"
Rem followed by "Sheet2MyCell"
Worksheets("Sheet1").Activate
MsgBox Range("MyCell").Value
Worksheets("Sheet2").Activate
MsgBox Range("MyCell").Value
SB It is not possible. Calc appears not to allow the same range name, e.g.
"MyCell", to exist on two or more worksheets [sheets].
Charts/Chart
Create a bar chart on the current worksheet [sheet] using the range "MyChartData".
VBA Sub SomeProcedure
Range("MyChartData").Select
Charts.Add
ActiveChart.ChartType = xlColumnClustered
ActiveChart.Name = "Sample Chart"
ActiveChart.SetSourceData _
Source:=Sheets("Example3").Range("ChartData"), _
PlotBy:= xlColumns
ActiveChart.Location Where:=xlLocationAsObject, _
Name:="Example3"
With ActiveChart
.HasTitle = True
.HasLegend = False
.ChartTitle.Characters.Text = "Sample Chart"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text =
"Category"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text =
"Amount"
End With
End Sub
SB Sub SomeProcedure
'define rectangle to hold chart
Dim aRect as new com.sun.star.awt.Rectangle
with aRect
.X = 8000 : .Y = 1000 : .Width = 16000 : .Height = 10000
end with
Reference: http://api.openoffice.org/docs/DevelopersGuide/Charts/Charts.htm#1+Charts
End Sub
SB Sub MyProc
ThisComponent.CurrentController.ActiveSheet. _
getCharts().removeByName("Sample Chart")
End Sub
Controls
This section describes placing controls, such as check boxes, option buttons, combo boxes,
on a worksheet [sheet].
Create a control (Check Box, Combo Box, Option Button, Button, etc.) on the worksheet
[sheet] and give the control a user defined name.
Excel • Drag and drop the controls from the Controls menu onto the worksheet
• Select the control on the worksheet and press right mouse button
• Select "Properties" option
• Enter user defined name into the "(Name)" property
Calc • Drag and drop the controls from the Forms Function menu onto the sheet
• Select the control on the sheet and press right mouse button
• Select the "Control..." option
• Select the "General" tab and enter user defined name into the "Name"
property
Usage Note: The Name property for option buttons in Calc is used to group option
buttons for selecting one and only one option from a group of options, radio button
operation. This same function in Excel is accomplished by assigning the same value to
the Group property of the option buttons.
Reference: OpenOffice Calc Help
Assign a worksheet [sheet] cell to hold current state of the control, i.e., is the check box
checked or unchecked, selected item in a combo box.
Excel • Turn Design Mode on
• Select the control on the workhseet and press right mouse button
• Select Properties option
• In the property LinkedCell enter a worksheet cell address (e.g., B4, $B$4)
or a user defined named range (e.g., "MyControlState")
Calc • Turn Design Mode on
• Select the control on the sheet and press right mouse button
• Select the Control... option
• Select Data tab and enter sheet cell address (e.g.,B4) into the Linked
Cell.... property.
Usage Note: Unable to use named ranges (e.g., "MyControlState") to specify a cell
location in Calc.
Assign to a list box or combo box the cell range on the worksheet [sheet] that holds the
list of items to display.
Excel • Turn Design Mode on
• Select the control on the workhseet and press right mouse button
• Select "Properties" option
• In the property "ListFillRange" enter a worksheet cell address (e.g., B4:B6,
$B$4:$B$6) or a user defined named range (e.g., "MyListOfChoices")
Calc • Turn Design Mode on
• Select the control on the sheet and press right mouse button
• Select the "Control..." option
• Select "Data" tab and enter sheet cell address (e.g.,B4:B6) into the "Source
Cell Range...." property.
UserForms
Create a UserForm [Dialog] "MyForm"
VBA • Start the Visual Basic IDE
Group related option buttons such that only one option button can be selected.
VBA Drag a Frame control to encompass the set of option buttons that are related.
SB On a Dialog, option buttons are grouped by consecutive Order attribute. To
access this attribute, select the option button, press right mouse button, select
Properties..... Consecutive numbers in the Order attribute are part of one
group. To designate another group, there has to be a break in the number.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+2+4+Opti
on+Button and http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XRadioButton.html
Sub MyProc
DialogLibraries.LoadLibrary("Standard")
oDlg = CreateUnoDialog(DialogLibraries.Standard.MyForm)
oDlg.execute()
End Sub
Usage Note: The oDlg variable is visible at the module level to all other procedures
that are accessing controls on the Dialog. This means all the procedures manipulating
or accessing controls on this Dialog panel are housed in a single module.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+1+1+Sho
wing+a+Dialog
Display message "Button Clicked" when the users clicks on button "MyButton"and then
disable the button.
VBA • Select button on the UserForm
Sub MyButton_Click
msgbox "Button Clicked"
oDlg.getControl("MyButton").Enable = False
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed. In the case of SB, the procedure name
is arbitrary. In the case of VBA, the procedure name is predefined by the Excel object
model.
Reference: http://api.openoffice.org/docs/common/ref/com/sun/star/awt/UnoControlButtonModel.html
else
end if
End sub
SB Dim oDlg as Object
Sub SomeProcedure
if oDlg.getControl("MyCheckBox").State = 1 then
else
end if
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed. In VBA the CheckBox value is either
False, True or Null (undetermined) and in SB it is a numeric value 0 (unchecked), 1
(checked) or 2 (undetermined).
Reference:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+2+3+Chec
k+Box and http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XCheckBox.html
End sub
SB Dim oDlg as Object
Sub SomeProcedure
with oDlg.getControl("MyListBox")
.addItem("Choice1",0)
.addItem("Choice2",1)
.addItem("Choice3",2)
end with
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed. When there are many items to load
into the ListBox, the method addItems(), provides a faster way of loading the ListBox.
Reference:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+2+7+List+
Box and http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XListBox.html
End sub
SB Dim oDlg as Object
Sub SomeProcedure
select case _
oDlg.getControl("MyListBox").SelectedText
case "Choice1"
'Do processing for "Choice1"
case "Choice2"
'Do processing for "Choice2"
case "Choice3"
'Do processing for "Choice3"
case else
'Something wrong do error processing
end select
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed.
Reference :
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+2+7+List+
Box and http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XListBox.html
End sub
SB Dim oDlg as Object
Sub SomeProcedure
with oDlg.getControl("MyComboBox")
.addItem("Choice1",0)
.addItem("Choice2",1)
.addItem("Choice3",2)
end with
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed. Like the ListBox, the ComboBox has
method addItems() to load many entries at once.
References:
http://api.openoffice.org/docs/DevelopersGuide/BasicAndDialogs/BasicAndDialogs.htm#1+5+2+8+Com
bo+Box and http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XComboBox.html
End sub
SB Dim oDlg as Object
Sub SomeProcedure
select case _
oDlg.getControl("MyComboBox").Text
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed. Please note the difference for
determining the selected choice between VBA and SB. In VBA the index value of the
selected choice is used, in SB, the text of the selected item is used.
Reference: http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XComboBox.htm l
For option buttons, "Option1", "Option2" and "Option3", determine which one is
selected.
VBA Sub SomeProcedure
If Option1.Value = True Then
' perform Option1 tasks
ElseIf Option2.Value = True Then
' perform Option2 tasks
ElseIf Option3.Value = True Then
' perform Option3 tasks
End If
End sub
SB Dim oDlg as Object
Sub SomeProcedure
End Sub
Usage Note: The oDlg variable is the same variable, visible at the module level, that
was used when the Dialog frame was displayed.
Porting Tasks
Steps taken to port the sample Excel/VBA workbook to Calc/SB spreadsheet.
Open Excel workbook in Calc. For the most part the general appearance of worksheets will
be the same in Calc. The following differences were noted after opening the Excel
workbook in Calc.
• On several worksheets the caption for the buttons do not appear the same. In Excel
buttons can be multi-lined. In Calc, multi-line captions do not appear to be supported.
• While all the VBA code was read in, all the statements were turned into comments by
prefixing "Rem" to each line. For existing VBA Modules, those modules exist in SB
under the same name, e.g., "ChartDemocode" and "SampleCode". For VBA code
associated with the workbook or worksheets, such as those executed by events or controls
on the worksheet, the code is contained in separate modules, one for each worksheet or for
the workbook. The workbook code is contained in a SB module called "ThisWorkbook".
Basic code for each worksheet is contained in a separate module named after the internal
Excel worksheet name. In this case the modules are called "Sheet1", "Sheet2", etc. VBA
code associated with the UserForm is contained in a module named the same as the Excel
Userform name. In this situation the module name is "UserForm1" Lastly, the "Rem"ed
statements are encased within a procedure definition that is named the same as the module
name.
• The UserForm panel itself did not transfer over. The UserFrom will have to be recreated
in a SB Dialog panel.
• All named cell ranges transferred over subject to the limitation of not being able to have a
same named cell in multiple worksheets.
• The text boxes on the various worksheets in Excel are transferred over to Calc. However,
not all the resulting objects in Calc allow the text to be modified. As of this writing, no
determination has been made on why some of the resulting text boxes allow modifications
and others do not.
Convert the workbook related procedures. These procedures are found in the module
"ThisWorkbook". Following are the steps to convert procedures in this module:
• Remove the encapsulating Sub ThisWorkbook (first statement) and End Sub (last
statement) statements. These are the encasing procedure statements that are automatically
inserted by Calc when reading in the Excel workbook.
Run-time Experiences
Porting and testing of the workbook [spreadsheet] was accomplished on the Windows/XP
platform. After porting on Windows was complete, the workbook [spreadsheet] was tested
on Linux. This section describes platform specific experiences of testing the ported
workbook [spreadsheet].
The Windows/XP environment:
• Operating System: Windows/XP Home with Service Pack 1
• OpenOffice: OpenOffice.org 1.1.1
The Linux environment:
• Operating System: SuSe Linux 9.1 (running under Vmware 4.5.1 on Windows/XP)
• OpenOffice: OpenOffice.org 1.1.1
After testing PortedExcelExamples.sxc on Windows, the workbook [spreadsheet] was
transferred to the Linux environment. The workbook [spreadsheet] performed the same on
Linux with the following exception:
• Although the button controls on the worksheets [sheets] were adjusted to display all the
text in the control's caption [label] for Windows, the text did not fit completely in the
buttons on OpenOffice on Linux. One way to avoid this problem is to specifically set the
font and character set size of the control and not just take the default specification when
the control is created. This specification is set through the Character Set property of the
control.
oSheet = ThisComponent.CurrentController.ActiveSheet
oCell = oSheet.getCellRangeByName("B3:E15")
Xray.XRay oCell 'this invokes the XRay tool for the oCell Object
Function CellRangeAddressString(oCellRng)
This function creates a string for the addresss of a cell or range object.
Parameters:
oCellRng – Object reference to cell or range object
function CellRangeAddressString(oCellRng as Object) as String
Dim FuncService
Rem Create service to access sheet functions
FuncService = _
createunoservice("com.sun.star.sheet.FunctionAccess")
case "ScCellRangeObj"
CellRangeAddressString = FuncService. _
CallFunction("ADDRESS", _
array(oCellRng.RangeAddress.StartRow+1, _
oCellRng.RangeAddress.StartColumn+1))
CellRangeAddressString = CellRangeAddressString _
& ":" & FuncService.CallFunction( _
"ADDRESS", _
array(oCellRng.RangeAddress.EndRow+1, _
oCellRng.RangeAddress.EndColumn+1))
end select
End Function
Function findSheetIndex(SheetName)
Function to find collection index for a worksheet [sheet]. The function will return either the
index value or -1 if the sheet is not found
Parameters:
for i = 0 to ThisComponent.Sheets.Count - 1
if ThisComponent.Sheets.getByIndex(i).Name = _
SheetName then
findSheetIndex = i
exit function
end if
next i
findSheetIndex = -1
End Function
ThisSheet = pCellRange.SpreadSheet
nRow = pCellRange.CellAddress.Row
StartRow = nRow
nColumn = pCellRange.CellAddress.Column
StartColumn = nColumn
StartContentType = pCellRange.getType()
EMPTYCELLTYPE = com.sun.star.table.CellContentType.EMPTY
ThisSheet.getCellByPosition(nColumn,nRow).getType() _
= EMPTYCELLTYPE) then
nColumn = nColumn - 1
exit do
elseif (StartContentType = EMPTYCELLTYPE and _
ThisSheet.getCellByPosition(nColumn,nRow).getType() _
<> EMPTYCELLTYPE) then
exit do
end if
nColumn = nColumn + 1
loop
ThisSheet.getCellByPosition(nColumn,nRow).getType() _
<> EMPTYCELLTYPE) then
exit do
end if
nRow = nRow - 1
loop
end select
'''make sure we are in bounds
if nColumn > 255 then
nColumn = 255
end if
if nColumn < 0 then
nColumn = 0
end if
if nRow > 31999 then
nRow = 31999
end if
if nRow < 0 then
nRow = 0
end if
MoveCursorToEnd = ThisSheet.getCellByPosition(nColumn,nRow)
end function
While Calc/SB does not, as of this writing, have a native Multi-Page control, it is possible to
craft equivalent functionality using the existing controls available in Calc/SB. The key
feature that allows this is each Control and Dialog panel itself have a property called Step.
When the Step value of a Control matches the Step value of the Dialog panel, that control is
visible, otherwise the Control is invisible.
The Step property takes on values 0, 1, 2, ... up to the maximum value of a Long variable.
Step value 0 signifies that the Control is visible at all times, regardless of the Step value of
the Dialog panel.
Note: A sample spreadsheet "Multi-page Form.sxc" demonstrates the concepts discussed
below.
To build the same functionality shown above, perform the following steps:
1. Create a Dialog panel Tools > Macros > Macro > Organizer... > New Dialog. Specify
Dialog panel name, e.g., "MultiPageDialog".
2. Select Edit to edit the newly created Dialog panel
3. Select the Dialog panel, press right-click the mouse, select Properties.... This will bring
Ensure the Page (step) property is set to 0. Usage Note: Selecting the Dialog panel requires
clicking the left mouse button when the mouse pointer is on the border (edge) of the Dialog
panel.
4. Place a Group Box Control on the Dialog panel to define the area where the multiple
pages will display. Clear the Label property for this Control.
5. Place two CommandButton Controls, adjacent to each other, at the outside, top left of the
Group Box Control to function as the Tabs. Change the Label property for the first
(leftmost) CommandButton to "Form Page 1" and the Name property to "TabForPage1".
For the second button change the Label and Name properties to "Form Page 2" and
"TabForPage2", respectively. Size each button as needed.
6. Place a single CommandButton at the bottom of the Dialog Panel, outside of the Group
Box Control and set its Label and Name property to "State Of Multi-Page" and
"CommandButton1", respectively, and size as needed.
7. Select the Dialog Control, press right-click mouse and select Properties.... Change Page
(step) property to "1". Now place the Controls for "Form Page 1" within the Group Box
Control. In this example, this is theCheckBox Control. Note: The Page (step) property
for any Control placed on the Dialog panel will take the value of the Page (step) proprerty
of the Dialog at the time the Control is created.
8. Select the Dialog Control and change the Page (step) property value to "2". Now place
the two OptionButton Controls within the Group Box Control for "Form Page 2".
Ensure the Order property for the two OptionButton buttons are consecutive numbers,
ensure that only of the OptionButton buttons can be selected at a time.
End Sub
End Sub
end Select
End With
End Sub
After completing the above steps, test the "MultiPageDialog" by executing the "Main"
procedure.
Final Tips & Tricks:
• After creating the Dialog, to display the different pages, change the Page (step) property
of the Dialog to 1 or 2 as desired.
• To move a Control, e.g., CommandButton, CheckBox, etc., from one page to another
page, select that Control, right-click mouse, select Properties... and alter Page (step)
property to match the value for the other page.
• An alternative to using CommandButtons to identify the page to display, a ListBox, with
the DropDown property set to True, can be used. In this situation, the page labels are
loaded into the ListBox entries (e.g., "Form Page 1"). Then based on the entry selected
in the ListBox the Page (step) property for the Dialog is set to the appropriate value. See
End Sub
• Another example for simulating the MultiPage function can be found in the spreadsheet
MyDataPilot.sxcdeveloped by Ian Laurenson
(http://homepages.paradise.net.nz/hillview/OOo/MyDataPilot.sxc). . It also has the
equivalent of a RefEdit control (a control for selecting a range on a spreadsheet from
within a dialog), text fields which only allow valid characters to be typed in, and a simple
tree control.
• It is possible to have the one routine called by events for more than one control, to know
which control called the event use an event parameter as shown is this example that could
be used as the associated code for the initiate event for the TabForPage button controls in
the above example:
Sub Page_Buttons_Click(oEvent)
with oDialog
'Change state of all tab controls
for i = 1 to 2
.getControl("TabForPage" & i).Model.State = 0
next
'Change the state of the one that was pressed
oEvent.source.model.state = 1
Bibliography
OpenOffice.org, Developer's Guide, August, 26, 2003,
http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html
Pitonyak, A., Useful Macro Information For OpenOffice, May 4, 2004,
http://www.pitonyak.org/AndrewMacro.sxw
Strome, D., How to Use BASIC Macros in OpenOffice.org, October 15, 2002,
http://documentation.openoffice.org/HOW_TO/various_topics/How_to_use_basic_macros.
sxw
Sun MicroSystems, StarOffice 7 Software Basic Programmer's Guide, July 2003,
http://docs.sun.com/db/doc/817-1826?q=StarOffice
Sun Microsystems, Migrating from Microsoft Office to StarOffice 7, January 2004,
http://se.sun.com/edu/staroffice/so_migration_guide_0104.pdf
Sun Microsystems, star module, 2003,
http://api.openoffice.org/docs/common/ref/com/sun/star/module-ix.html
1.1. "Commercial Use" means distribution or otherwise making 2.1 Initial Writer Grant.
the Documentation available to a third party.
The Initial Writer hereby grants You a world-wide, royalty-
1.2. "Contributor" means a person or entity who creates or free, non-exclusive license to use, reproduce, prepare
contributes to the creation of Modifications. Modifications of, compile, publicly perform, publicly display,
demonstrate, market, disclose and distribute the
1.3. "Documentation" means the Original Documentation or Documentation in any form, on any media or via any
Modifications or the combination of the Original Electronic Distribution Mechanism or other method now
Documentation and Modifications, in each case including known or later discovered, and to sublicense the foregoing
portions thereof. rights to third parties through multiple tiers of sublicensees in
accordance with the terms of this License.
1.4. "Electronic Distribution Mechanism" means a mechanism
generally accepted for the electronic transfer of data. The license rights granted in this Section 2.1 ("Initial Writer
Grant") are effective on the date Initial Writer first distributes
1.5. "Initial Writer" means the individual or entity identified as Original Documentation under the terms of this License.
the Initial Writer in the notice required by the Appendix.
2.2. Contributor Grant.
1.6. "Larger Work" means a work which combines
Documentation or portions thereof with documentation or Each Contributor hereby grants You a world-wide, royalty-
other writings not governed by the terms of this License. free, non-exclusive license to use, reproduce, prepare
Modifications of, compile, publicly perform, publicly display,
1.7. "License" means this document. demonstrate, market, disclose and distribute the
1.8. "Modifications" means any addition to or deletion from the Documentation in any form, on any media or via any
substance or structure of either the Original Documentation or Electronic Distribution Mechanism or other method now
any previous Modifications, such as a translation, abridgment, known or later discovered, and to sublicense the foregoing
condensation, or any other form in which the Original rights to third parties through multiple tiers of sublicensees in
Documentation or previous Modifications may be recast, accordance with the terms of this License.
transformed or adapted. A work consisting of editorial The license rights granted in this Section 2.2 ("Contributor
revisions, annotations, elaborations, and other modifications Grant") are effective on the date Contributor first makes
which, as a whole represent an original work of authorship, is a Commercial Use of the Documentation.
Modification. For example, when Documentation is released
as a series of documents, a Modification is: 3.0 DISTRIBUTION OBLIGATIONS.
A. Any addition to or deletion from the contents of the Original 3.1. Application of License.
Documentation or previous Modifications.
The Modifications which You create or to which You
B. Any new documentation that contains any part of the contribute are governed by the terms of this License, including
Original Documentation or previous Modifications. without limitation Section 2.2 ("Contributor Grant"). The
Documentation may be distributed only under the terms of this
1.9. "Original Documentation" means documentation described License or a future version of this License released in
as Original Documentation in the notice required by the accordance with Section 5.0 ("Versions of the License"), and
Appendix, and which, at the time of its release under this You must include a copy of this License with every copy of the
License is not already Documentation governed by this Documentation You distribute. You may not offer or impose
License. any terms that alter or restrict the applicable version of this
1.10. "Editable Form" means the preferred form of the License or the recipients' rights hereunder. However, You may
Documentation for making Modifications to it. The include an additional document offering the additional rights
Documentation can be in an electronic, compressed or archival described in Section 3.5 ("Required Notices").
form, provided the appropriate decompression or de-archiving 3.2. Availability of Documentation.
software is widely available for no charge.
Any Modification which You create or to which You
1.11. "You" (or "Your") means an individual or a legal entity contribute must be made available publicly in Editable Form
exercising rights under, and complying with all of the terms of under the terms of this License via a fixed medium or an
this License or a future version of this License issued under accepted Electronic Distribution Mechanism.
Section 5.0 ("Versions of the License"). For legal entities,
"You" includes any entity which controls, is controlled by, or 3.3. Description of Modifications.
is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to All Documentation to which You contribute must identify the
cause the direction or management of such entity, whether by changes You made to create that Documentation and the date
contract or otherwise, or (b) ownership of more than fifty of any change. You must include a prominent statement that
percent (50%) of the outstanding shares or beneficial the Modification is derived, directly or indirectly, from
ownership of such entity. Original Documentation provided by the Initial Writer and
include the name of the Initial Writer in the Documentation or under the terms of that version. You may also choose to use
via an electronic link that describes the origin or ownership of such Documentation under the terms of any subsequent version
the Documentation. The foregoing change documentation may of the License published by __________________ [Insert
be created by using an electronic program that automatically name of the foundation, company, Initial Writer, or whoever
tracks changes to the Documentation, and such changes must may modify this License]. No one other than
be available publicly for at least five years following release of ________________________[Insert name of the foundation,
the changed Documentation. company, Initial Writer, or whoever may modify this License]
has the right to modify the terms of this License. Filling in the
3.4. Intellectual Property Matters. name of the Initial Writer, Original Documentation or
Contributor in the notice described in the Appendix shall not
Contributor represents that Contributor believes that be deemed to be Modifications of this License.
Contributor's Modifications are Contributor's original creation
(s) and/or Contributor has sufficient rights to grant the rights 6.0 DISCLAIMER OF WARRANTY.
conveyed by this License.
DOCUMENTATION IS PROVIDED UNDER THIS
3.5. Required Notices. LICENSE ON AN "AS IS'' BASIS, WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
You must duplicate the notice in the Appendix in each file of INCLUDING, WITHOUT LIMITATION, WARRANTIES
the Documentation. If it is not possible to put such notice in a THAT THE DOCUMENTATION IS FREE OF DEFECTS,
particular Documentation file due to its structure, then You MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
must include such notice in a location (such as a relevant OR NON-INFRINGING. THE ENTIRE RISK AS TO THE
directory) where a reader would be likely to look for such a QUALITY, ACCURACY, AND PERFORMANCE OF THE
notice, for example, via a hyperlink in each file of the DOCUMENTATION IS WITH YOU. SHOULD ANY
Documentation that takes the reader to a page that describes DOCUMENTATION PROVE DEFECTIVE IN ANY
the origin and ownership of the Documentation. If You RESPECT, YOU (NOT THE INITIAL WRITER OR ANY
created one or more Modification(s) You may add your name OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
as a Contributor to the notice described in the Appendix. NECESSARY SERVICING, REPAIR OR CORRECTION.
You must also duplicate this License in any Documentation THIS DISCLAIMER OF WARRANTY CONSTITUTES AN
file (or with a hyperlink in each file of the Documentation) ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY
where You describe recipients' rights or ownership rights. DOCUMENTATION IS AUTHORIZED HEREUNDER
EXCEPT UNDER THIS DISCLAIMER.
You may choose to offer, and to charge a fee for, warranty,
support, indemnity or liability obligations to one or more 7.0 TERMINATION.
recipients of Documentation. However, You may do so only on This License and the rights granted hereunder will terminate
Your own behalf, and not on behalf of the Initial Writer or any automatically if You fail to comply with terms herein and fail
Contributor. You must make it absolutely clear than any such to cure such breach within 30 days of becoming aware of the
warranty, support, indemnity or liability obligation is offered breach. All sublicenses to the Documentation which are
by You alone, and You hereby agree to indemnify the Initial properly granted shall survive any termination of this License.
Writer and every Contributor for any liability incurred by the Provisions which, by their nature, must remain in effect beyond
Initial Writer or such Contributor as a result of warranty, the termination of this License shall survive.
support, indemnity or liability terms You offer.
8.0 LIMITATION OF LIABILITY.
3.6. Larger Works.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL
You may create a Larger Work by combining Documentation THEORY, WHETHER IN TORT (INCLUDING
with other documents not governed by the terms of this NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL
License and distribute the Larger Work as a single product. In THE INITIAL WRITER, ANY OTHER CONTRIBUTOR, OR
such a case, You must make sure the requirements of this ANY DISTRIBUTOR OF DOCUMENTATION, OR ANY
License are fulfilled for the Documentation. SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO
4.0 APPLICATION OF THIS LICENSE. ANY PERSON FOR ANY DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF
This License applies to Documentation to which the Initial ANY CHARACTER INCLUDING, WITHOUT
Writer has attached this License and the notice in the LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
Appendix. WORK STOPPAGE, COMPUTER FAILURE OR
MALFUNCTION, OR ANY AND ALL OTHER DAMAGES
5.0 VERSIONS OF THE LICENSE. OR LOSSES ARISING OUT OF OR RELATING TO THE
USE OF THE DOCUMENTATION, EVEN IF SUCH PARTY
5.1. New Versions. SHALL HAVE BEEN INFORMED OF THE POSSIBILITY
OF SUCH DAMAGES.
Initial Writer may publish revised and/or new versions of the
License from time to time. Each version will be given a 9.0 U.S. GOVERNMENT END USERS.
distinguishing version number.
If Documentation is being acquired by or on behalf of the U.S.
5.2. Effect of New Versions. Government or by a U.S. Government prime contractor or
subcontractor (at any tier), then the Government's rights in
Once Documentation has been published under a particular Documentation will be only as set forth in this Agreement; this
version of the License, You may always continue to use it is in accordance with 48 CFR 227.7201 through 227.7202-4
(for Department of Defense (DOD) acquisitions) and with 48 Documentation License Version 1.0 (the "License"); you may
CFR 2.101 and 12.212 (for non-DOD acquisitions). only use this Documentation if you comply with the terms of
this License. A copy of the License is available at
10.0 MISCELLANEOUS. http://www.openoffice.org/licenses/PDL.rtf.
This License represents the complete agreement concerning the The Original Documentation is _________________. The
subject matter hereof. If any provision of this License is held to Initial Writer of the Original Documentation is
be unenforceable, such provision shall be reformed only to the ______________________ (C) ____. All Rights Reserved.
extent necessary to make it enforceable. This License shall be (Initial Writer contact(s):_______________[Insert
governed by California law, excluding its conflict-of-law hyperlink/alias].)
provisions. With respect to disputes or any litigation relating to
this License, the losing party is responsible for costs, including Contributor(s):
without limitation, court costs and reasonable attorneys' fees ______________________________________.
and expenses. The application of the United Nations
Convention on Contracts for the International Sale of Goods is Portions created by ______ are Copyright (C)_________[Insert
expressly excluded. Any law or regulation which provides that year(s)]. All Rights Reserved. (Contributor contact(s):
the language of a contract shall be construed against the drafter ________________[Insert hyperlink/alias]).
shall not apply to this License.
Note: The text of this Appendix may differ slightly from the
Appendix text of the notices in the files of the Original Documentation.
You should use the text of this Appendix rather than the text
Public Documentation License Notice found in the Original Documentation for Your Modifications.
The contents of this Documentation are subject to the Public