The ScriptForge.Basic service proposes a collection of Office Basic methods to be executed in a Python context. Basic service methods reproduce the exact syntax and behaviour of Basic builtin functions.
Typical example:
bas.MsgBox('Display this text in a message box from a Python script')
ScriptForge.Basic service is limited to Python scripts.
Before using the Basic service, import the CreateScriptService() method from the scriptforge module:
from scriptforge import CreateScriptService
bas = CreateScriptService("Basic")
Name | ReadOnly | Type | Description |
---|---|---|---|
MB-OK, MB-OKCANCEL, MB-RETRYCANCEL, MB-YESNO, MB-YESNOCANCEL | Yes | Integer | Values: 0, 1, 5, 4, 3 |
MB-ICONEXCLAMATION, MB-ICONINFORMATION, MB-ICONQUESTION, MB-ICONSTOP | Yes | Integer | Values: 48, 64, 32, 16 |
MB-ABORTRETRYIGNORE, MB-DEFBUTTON1, MB-DEFBUTTON2, MB-DEFBUTTON3 | Yes | Integer | Values: 2, 128, 256, 512 |
IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES | Yes | Integer | Values: 3, 2, 5, 7, 1, 4, 6Constants indicating MsgBox selected button. |
StarDesktop | Yes | UNOobject | StarDesktop object represents Office Start Centre. |
Converts a numeric expression or a string to a datetime.datetime Python native object.
This method exposes the Basic builtin function CDate to Python scripts.
svc.CDate(expression: any): obj
expression: a numeric expression or a string representing a date.
When you convert a string expression, the date and time must be entered either in one of the date acceptance patterns defined for your locale setting (see Tools - Options - Language Settings - Languages) or in ISO date format (momentarily, only the ISO format with hyphens, e.g. "2012-12-31" is accepted). In numeric expressions, values to the left of the decimal represent the date, beginning from December 31, 1899. Values to the right of the decimal represent the time.
d = bas.CDate(1000.25)
bas.MsgBox(str(d)) # 1902-09-26 06:00:00
bas.MsgBox(d.year) # 1902
Converts a UNO date/time representation to a datetime.datetime Python native object.
svc.CDateFromUnoDateTime(unodate: uno): obj
unodate: A UNO date/time object of one of the following types: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time
The following example creates a com.sun.star.util.DateTime object and converts it to a datetime.datetime Python object.
import uno
uno-date = uno.createUnoStruct('com.sun.star.util.DateTime')
uno-date.Year = 1983
uno-date.Month = 2
uno-date.Day = 23
new-date = bas.CDateFromUnoDateTime(uno-date)
bas.MsgBox(str(new-date)) # 1983-02-23 00:00:00
Converts a date representation into a com.sun.star.util.DateTime object.
svc.CDateToUnoDateTime(date: obj): uno
date: A Python date/time object of one of the following types: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct-time.
from datetime import datetime
current-datetime = datetime.now()
uno-date = bas.CDateToUnoDateTime(current-datetime)
bas.MsgBox(str(uno-date.Year) + "-" + str(uno-date.Month) + "-" + str(uno-date.Day))
Returns a system path file name for the given file: URL.
svc.ConvertFromUrl(url: str): str
url: An absolute file: URL.
A system path file name.
filename = bas.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/Office/News.txt")
bas.MsgBox(filename)
Returns a file: URL for the given system path.
svc.ConvertToUrl(systempath: str): str
systempath: A system file name as a string.
A file: URL as a string.
url = bas.ConvertToUrl( 'C:\Program Files(x86)\Office\News.txt')
bas.MsgBox(url)
Instantiates a UNO service with the ProcessServiceManager.
svc.CreateUnoService(servicename: str): uno
servicename: A fully qualified service name such as com.sun.star.ui.dialogs.FilePicker or com.sun.star.sheet.FunctionAccess.
dsk = bas.CreateUnoService('com.sun.star.frame.Desktop')
Adds a date or time interval to a given date/time a number of times and returns the resulting date.
svc.DateAdd(interval: str, number: num, date: datetime): datetime
interval: A string expression from the following table, specifying the date or time interval.
interval (string value) | Explanation |
---|---|
yyyy | Year |
q | Quarter |
m | Month |
y | Day of year |
w | Weekday |
ww | Week of year |
d | Day |
h | Hour |
n | Minute |
s | Second |
number: A numerical expression specifying how often the interval value will be added when positive or subtracted when negative.
date: A given datetime.datetime value, the interval value will be added number times to this datetime.datetime value.
A datetime.datetime value.
dt = datetime.datetime(2004, 1, 31)
dt = bas.DateAdd("m", 1, dt)
print(dt)
Returns the number of date or time intervals between two given date/time values.
svc.DateDiff(interval: str, date1: datetime, date2: datetime, firstdayofweek = 1, firstweekofyear = 1): int
interval: A string expression specifying the date interval, as detailed in above DateAdd method.
date1, date2: The two datetime.datetime values to be compared.
firstdayofweek: An optional parameter that specifies the starting day of a week.
firstdayofweek value | Explanation |
---|---|
0 | Use system default value |
1 | Sunday (default) |
2 | Monday |
3 | Tuesday |
4 | Wednesday |
5 | Thursday |
6 | Friday |
7 | Saturday |
firstweekofyear: An optional parameter that specifies the starting week of a year.
firstweekofyear value | Explanation |
---|---|
0 | Use system default value |
1 | Week 1 is the week that includes 1st January (default) |
2 | Week 1 is the first week containing four or more days of that year |
3 | Week 1 is the first week containing only days of the new year |
A number.
date1 = datetime.datetime(2005,1, 1)
date2 = datetime.datetime(2005,12,31)
diffDays = bas.DateDiff('d', date1, date2)
print(diffDays)
The DatePart function returns a specified part of a date.
svc.DatePart(interval: str, date: datetime, firstdayofweek = 1, firstweekofyear = 1): int
interval: A string expression specifying the date interval, as detailed in above DateAdd method.
date: The date/time from which the result is calculated.
firstdayofweek, firstweekofyear: optional parameters that respectively specify the starting day of a week and the starting week of a year, as detailed in above DateDiff method.
The extracted part for the given date/time.
print(bas.DatePart("ww", datetime.datetime(2005,12,31)
print(bas.DatePart('q', datetime.datetime(1999,12,30)
Computes a date value from a date string.
svc.DateValue(date: str): datetime
date: A string that contains the date that will be converted to a Date object.
The string passed to DateValue must be expressed in one of the date formats defined by your locale setting (see Tools - Options - Language Settings - Languages) or using the ISO date format "yyyy-mm-dd" (year, month and day separated by hyphens).
The computed date.
dt = bas.DateValue("23-02-2011")
print(dt)
Converts a number to a string, and then formats it according to the format that you specify.
svc.Format(expression: any, format = ''): str
expression: Numeric expression that you want to convert to a formatted string.
format: String that specifies the format code for the number. If format is omitted, the Format function works like the Office Basic Str() function.
Text string.
The following list describes the codes that you can use for formatting a numeric expression:
0: If expression has a digit at the position of the 0 in the format code, the digit is displayed, otherwise a zero is displayed.
If expression has fewer digits than the number of zeros in the format code, (on either side of the decimal), leading or trailing zeros are displayed. If the expression has more digits to the left of the decimal separator than the amount of zeros in the format code, the additional digits are displayed without formatting.
Decimal places in the expression are rounded according to the number of zeros that appear after the decimal separator in the format code.
#: If expression contains a digit at the position of the # placeholder in the format code, the digit is displayed, otherwise nothing is displayed at this position.
This symbol works like the 0, except that leading or trailing zeroes are not displayed if there are more # characters in the format code than digits in the expression. Only the relevant digits of the expression are displayed.
.: The decimal placeholder determines the number of decimal places to the left and right of the decimal separator.
If the format code contains only # placeholders to the left of this symbol, numbers less than 1 begin with a decimal separator. To always display a leading zero with fractional numbers, use 0 as a placeholder for the first digit to the left of the decimal separator.
%: Multiplies the expressionby 100 and inserts the percent sign (%) where the expression appears in the format code.
E- E+ e- e+ : If the format code contains at least one digit placeholder (0 or #) to the right of the symbol E-, E+, e-, or e+, the expression is formatted in the scientific or exponential format. The letter E or e is inserted between the number and the exponent. The number of placeholders for digits to the right of the symbol determines the number of digits in the exponent.
If the exponent is negative, a minus sign is displayed directly before an exponent with E-, E+, e-, e+. If the exponent is positive, a plus sign is only displayed before exponents with E+ or e+.
The thousands delimiter is displayed if the format code contains the delimiter enclosed by digit placeholders (0 or #).
The use of a period (dot) as a decimal separator is dependent on the regional setting. When you enter a number directly in Basic source code, always use a dot-on-the-line as decimal delimiter. The actual character displayed as a decimal separator depends on the number format in your system settings.
- + $ ( ) space: A plus (+), minus (-), dollar ($), space, or brackets entered directly in the format code is displayed as a literal character.
To display characters other than the ones listed here, you must precede it by a backslash (\), or enclose it in quotation marks (" ").
\ : The backslash displays the next character in the format code.
Characters in the format code that have a special meaning can only be displayed as literal characters if they are preceded by a backslash. The backslash itself is not displayed, unless you enter a double backslash (\\) in the format code.
Characters that must be preceded by a backslash in the format code in order to be displayed as literal characters are date- and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, :), numeric-formatting characters (#, 0, %, E, e, comma, dot-on-the-line) and string-formatting characters (@, &, <, >, !).
You can also use the following predefined number formats. Except for "General Number", all of the predefined format codes return the number as a decimal number with two decimal places.
If you use predefined formats, the name of the format must be enclosed by quotation marks.
General Number: Numbers are displayed as entered.
Currency: Inserts a dollar sign in front of the number and encloses negative numbers in brackets ( ).
Fixed: Displays at least one digit in front of the decimal separator.
Standard: Displays numbers with a thousands separator.
Percent: Multiplies the number by 100 and appends a percent sign to the number.
Scientific: Displays numbers in scientific format (for example, 1.00E+03 for 1000).
A format code can be divided into three sections that are separated by semicolons. The first part defines the format for positive values, the second part for negative values, and the third part for zero. If you only specify one format code, it applies to all numbers.
You can set the locale used for controlling the formatting numbers, dates and currencies in Office Basic in Tools - Options - Language Settings - Languages. In Basic format codes, the decimal point (.) is always used as placeholder for the decimal separator defined in your locale and will be replaced by the corresponding character.
The same applies to the locale settings for date, time and currency formats. The Basic format code will be interpreted and displayed according to your locale setting.
txt = bas.Format(6328.2, '##.##0.00')
print(txt)
Returns the default context of the process service factory, if existent, else returns a null reference.
GetDefaultContext is an alternative to the getComponentContext() method available from XSCRIPTCONTEXT global variable or from uno.py module.
svc.GetDefaultContext(): uno
The default component context is used, when instantiating services via XMultiServiceFactory. See the Professional UNO chapter in the Developer's Guide on api.libreoffice.org for more information.
ctx = bas.GetDefaultContext()
Returns a numerical value that specifies the graphical user interface. This function is only provided for backward compatibility with previous versions.
Refer to system() method from platform Python module to identify the operating system.
svc.GetGuiType(): int
n = bas.GetGuiType()
Returns the operating system-dependent directory separator used to specify file paths.
Use os.pathsep from os Python module to identify the path separator.
svc.GetPathSeparator(): str
sep = bas.GetPathSeparator()
Returns the number of system ticks provided by the operating system. You can use this function to optimise certain processes. Use this method to estimate time in milliseconds:
svc.GetSystemTicks(): int
ticks-ini = bas.GetSystemTicks()
time.sleep(1)
ticks-end = bas.GetSystemTicks()
bas.MsgBox("{} - {} = {}".format(ticks-end, ticks-ini,ticks-end - ticks-ini))
Returns the UNO object containing all shared Basic libraries and modules.
This method is the Python equivalent to GlobalScope.BasicLibraries in Basic scripts.
svc.GlobalScope.BasicLibraries(): uno
com.sun.star.script.XLibraryContainer
The following example loads the Gimmicks Basic library if it has not been loaded yet.
libs = bas.GlobalScope.BasicLibraries()
if not libs.isLibraryLoaded("Gimmicks"):
libs.loadLibrary("Gimmicks")
Returns the UNO object containing all shared dialog libraries.
This method is the Python equivalent to GlobalScope.DialogLibraries in Basic scripts.
svc.GlobalScope.DialogLibraries(): uno
com.sun.star.comp.sfx2.DialogLibraryContainer
The following example shows a message box with the names of all available dialog libraries.
dlg-libs = bas.GlobalScope.DialogLibraries()
lib-names = dlg-libs.getElementNames()
bas.MsgBox("\n".join(lib-names))
svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str
prompt: String expression displayed as the message in the dialogue box.
title: String expression displayed in the title bar of the dialogue box.
default: String expression displayed in the text box as default if no other input is given.
xpostwips: Integer expression that specifies the horizontal position of the dialogue box. The position is an absolute coordinate and does not refer to the window of Office.
ypostwips: Integer expression that specifies the vertical position of the dialogue box. The position is an absolute coordinate and does not refer to the window of Office.
If xpostwips and ypostwips are omitted, the dialogue box is centred on the screen. The position is specified in twips.
String
txt = s.InputBox('Please enter a phrase:', "Dear user")
s.MsgBox(txt, s.MB-ICONINFORMATION, "Confirmation of phrase")
For in-depth information please refer to Input/Output to Screen with Python on the Wiki.
Displays a dialogue box containing a message and returns an optional value.
MB-xx constants help specify the dialogue box type, the number and type of buttons to display, plus the icon type. By adding their respective values they form bit patterns, that define the MsgBox dialogue box appearance.
bas.MsgBox(prompt: str, [buttons: int], [title: str])[: int]
prompt: String expression displayed as a message in the dialogue box. Line breaks can be inserted with Chr$(13).
title: String expression displayed in the title bar of the dialogue box. If omitted, the title bar displays the name of the respective application.
buttons: Any integer expression that specifies the dialogue box type, as well as the number and type of buttons to display, and the icon type. buttons represents a combination of bit patterns, that is, a combination of elements can be defined by adding their respective values:
An optional integer as detailed in above IDxx properties.
txt = s.InputBox('Please enter a phrase:', "Dear user")
s.MsgBox(txt, s.MB-ICONINFORMATION, "Confirmation of phrase")
For in-depth information please refer to Input/Output to Screen with Python on the Wiki.
Returns the current system date and time as a datetime.datetime Python native object.
svc.Now(): datetime
bas.MsgBox(bas.Now(), bas.MB-OK, "Now")
Returns an integer colour value consisting of red, green, and blue components.
svc.RGB(red:int, green: int, blue: int): int
red: Any integer expression that represents the red component (0-255) of the composite colour.
green: Any integer expression that represents the green component (0-255) of the composite colour.
blue: Any integer expression that represents the blue component (0-255) of the composite colour.
The resulting Long value is calculated with the following formula:
Result = red×65536 + green×256 + blue.
Under VBA compatibility mode (Option VBASupport 1), the Long value is calculated as
Result = red + green×256 + blue×65536
The colour picker dialogue box helps computing red, green and blue components of a composite colour. Changing the colour of text and selecting Custom colour displays the color picker dialogue box.
Integer
YELLOW = bas.RGB(255,255,0)
If the current component refers to a Office document, this method returns the UNO object representing the document.
The method will return None when the current component does not correspond to a document.
svc.ThisComponent(): uno
comp = bas.ThisComponent
bas.MsgBox("\n".join(comp.getSupportedServiceNames()))
If the script is being executed from a Base document or any of its subcomponents this method returns the main component of the Base instance.
This method returns None otherwise.
svc.ThisDatabaseDocument(): uno
db-doc = bas.ThisDatabaseDocument
table-names = db-doc.DataSource.getTables().getElementNames()
bas.MsgBox("\n".join(table-names))
Visit the OfficeDatabaseDocument API page to learn more about Base's main component structure.
Inspect Uno objects or variables.
svc.Xray(obj: any)
obj: A variable or UNO object.
bas.Xray(bas.StarDesktop)
All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "-" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.