Text Documents (Writer)
HTML Documents (Writer Web)
Spreadsheets (Calc)
Presentations (Impress)
Drawings (Draw)
Database Functionality (Base)
Formulae (Math)
Charts and Diagrams
Macros and Scripting
Office Installation
Common Help Topics
OneOffice Logo

Calling Basic Macros from Python

You can call Office Basic macros from Python scripts, and notable features can be obtained in return such as:

  • Simple logging facilities out of Access2Base library Trace console,
  • InputBox and MsgBox screen I/O functions based on Basic to ease Python development,
  • Xray calls interrupting Python script execution to help inspect variables.

The Office Application Programming Interface (API) Scripting Framework supports inter-language script execution between Python and Basic, or other supported programming languages for that matter. Arguments can be passed back and forth across calls, provided that they represent primitive data types that both languages recognise, and assuming that the Scripting Framework converts them appropriately.

It is recommended to have knowledge of Python standard modules and Office API features prior to perform inter-language calls from Python to Basic, JavaScript or any other script engine.

When running Python scripts from an Integrated Development Environment (IDE), the Office-embedded Basic engine may be absent. Avoid Python-to-Office Basic calls in such contexts. However Python environment and Universal Networks Objects (UNO) are fully available. Refer to Setting Up an Integrated IDE for Python for more information.

Retrieving Office Basic Scripts

Office Basic macros can be personal, shared, or embedded in documents. In order to execute them, Python run time needs to be provided with Basic macro locations. Implementing the com.sun.star.script.provider.XScriptProvider interface allows the retrieval of executable scripts:

		 import uno
		 from com.sun.star.script.provider import Xscript
		 def getBasicScript(macro='Main', module='Module1', library='Standard',
		         isEmbedded=False) -> XScript:
		     '''Grab Basic script object before invocation.'''
		     ctx = uno.getComponentContext()
		     smgr = ctx.ServiceManager
		     if isEmbedded:
		         desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)
		         scriptPro = desktop.CurrentComponent.getScriptProvider()
		         location = "document"
		         mspf = smgr.createInstanceWithContext(
		             "com.sun.star.script.provider.MasterScriptProviderFactory", ctx)
		         scriptPro = mspf.createScriptProvider("")
		         location = "application"
		     scriptName = "vnd.sun.star.script:"+library+"."+module+"."+macro+ \
		     xScript = scriptPro.getScript(scriptName)
		     return xScript

Executing Office Basic Scripts

The Office Software Development Kit (SDK) documentation for com.sun.star.script.provider.XScript interface details the calling convention for inter-language calls. Invocation of functions requires three arrays:

  • the first lists the arguments of the called routine
  • the second identifies modified arguments
  • the third stores the return values

Python Syntax

results = script.invoke((prompt,buttons,title), (), ())

script.invoke((message,), tuple, ())

script.invoke((args), (), results)

Examples of Personal or Shared Scripts

Examples in Input/Output to Screen detail Python to Basic invocation calls. Monitoring Document Events illustrates the usage of *args Python idiom to print a variable number of parameters to Access2Base logging console dialog.

At time of development you can interrupt Python script execution using Xray extension in order to inspect properties and methods of UNO objects. The APSO extension debugger allows object introspection using either Xray either MRI extensions.

	  def xray(myObject):
	  	  script = getBasicScript(library="XrayTool", module="-Main", macro="Xray")
	  	  script.invoke((myObject,), (), ())

Examples of Embedded Scripts in Documents

*argsPython simplified syntax can be used in conjunction with Office Basic routines that accept a variable number of arguments. Below Print and SUM Python functions call their Basic Print and SUM counterparts, using aforementioned getBasicScript function. Exception handling is not detailed.

	  # -*- coding: utf-8 -*-
	  from --future-- import unicode-literals
	  def Print(*args):
	      """Outputs the specified strings or numeric expressions in a dialog box."""
	      xScript = getBasicScript("Print", "Scripting", embedded=True)
	      xScript.invoke((args), (), ())
	  def SUM(*args):
	      """SUM the specified number expression."""
	      xScript = getBasicScript("SUM", "Scripting", embedded=True)
	      res = xScript.invoke((args), (), ())
	      return res[0]
	  # def getBasicScript()  # see above
	  def playWithArgs():
	      Print("Fun with *args ", -9.81, 297864.681974, 8762E-137)
	      Print(SUM(45, -9.81, 297864.681974))
	      Print(SUM(45, -9.81, 297864.681974, 8762E+137))
	  g-exportedScripts = (playWithArgs,)

The Office Basic Print and SUM document-based routines accept a variable number of arguments. The Private or Public attributes have no effect. The arguments type checking is skipped for clarity.

	  Option Compatible ' "Standard.Scripting" module
	  Option Explicit
	  Private Sub Print(ParamArray args() As Variant, Optional sep As String = " ")
	      ''' Print item list of variable number '''
	      ' all CStr() convertible args are accepted
	      Dim str As String, i As Integer
	      If UBound(args) >= 0 Then
	          For i = 0 To UBound(args)
	              str = str + Cstr(args(i))+ sep 
	          Next i
	      End If
	      Print str
	  End Sub ' Standard.Scripting.Print()
	  Public Function SUM(ParamArray args() As Variant) As Variant
	      ''' SUM a variable list of numbers '''
	      Dim ndx As Integer
	      If UBound(args) >= 0 Then
	          For ndx = 0 To UBound(args)
	              SUM = SUM + args(ndx)
	          Next ndx
	      End If
	  End Function ' Standard.Scripting.SUM()