These decorators, functions and classes are used to expose Python functions to Excel as macro functions (Subs).
Please see Macro Functions for complete details on writing Excel macro function in Python.
See also Type Conversion.
xl_macro is a decorator for exposing python functions to Excel as macros. Macros can be triggered from controls, from VBA or using COM.
signature (str) –
An optional string that specifies the argument types and, optionally, their names and the return type.
The format of the signature is identical to the one used by xl_func
.
If no signature is provided the argument and return types will be inferred from any type annotations,
and if there are no type annotations then the types will be assumed to be var
.
allow_abort (bool) – If True the function may be cancelled by the user pressing Esc. A KeyboardInterrupt exception is raised when Esc is pressed. If not specified the behavior is determined by the allow_abort setting in the config (see PyXLL Settings).
name (string) – The Excel macro name. If None, the Python function name is used.
shortcut (string) –
Assigns a keyboard shortcut to the macro. Shortcuts should be one or more modifier key names (Ctrl, Shift or Alt) and a key, separated by the ‘+’ symbol. For example, ‘Ctrl+Shift+R’.
If the same key combination is already in use by Excel it may not be possible to assign a macro to that combination.
Macros can also have keyboard shortcuts assigned in the config file (see configuration).
transpose (boolean) – If true, if an array is returned it will be transposed before being returned to Excel.
nan_value –
Value to use in the case that the return value is NaN
.
Defaults to the global setting nan_value
set in the config file, or #NUM!
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
posinf_value –
Value to use in the case that the return value is +Inf
.
Defaults to the global setting posinf_value
set in the config file, or Excel’s own numeric representation of +Inf
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
neginf_value –
Value to use in the case that the return value is -Inf
.
Defaults to the global setting neginf_value
set in the config file, or Excel’s own numeric representation of -Inf
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
none_value –
Value to use in the case that the return value is None
.
Defaults to the global setting none_value
set in the config file. If not set, the Excel NULL
value is used
which gets displayed as 0
by default.
@Since PyXLL 5.9.0
automatic_calculations –
Disable automatic calculations until finished.
@Since PyXLL 5.9.0
screen_updating –
Disable screen updating until finished.
@Since PyXLL 5.9.0
disable_alerts –
Disable alerts until finished.
@Since PyXLL 5.9.0
restore_selection –
Restore the current selection when finished.
@Since PyXLL 5.9.0
restore_active_sheet –
Restore the current active sheet when finished.
@Since PyXLL 5.9.0
Example usage:
from pyxll import xl_macro, xlcAlert
@xl_macro
def popup_messagebox():
"""pops up a message box"""
xlcAlert("Hello")
@xl_macro
def py_strlen(s):
"""returns the length of s"""
return len(s)
See Macro Functions for more details about using the xl_macro decorator.
Gets the Excel Application COM object and returns it as a win32com.Dispach
,
comtypes.POINTER(IUknown)
, pythoncom.PyIUnknown
or xlwings.App
object, depending on which COM package
is being used.
Many methods and properties Excel Application COM object will fail if called from outside of an
Excel macro context. Generally, xl_app
should only be used from Python code called from an
Excel macro [1], menu [1], or worksheet function [1] [2]. To use
it from any other context, or from a background thread, schedule a call using schedule_call
.
com_package (string) – The Python package to use when returning the COM object. It should be None, ‘win32com’, ‘comtypes’, ‘pythoncom’ or ‘xlwings’. If None the com package set in the configuration file will be used, or ‘win32com’ if nothing is set.
The Excel Application COM object using the requested COM package.
Warning
Excel COM objects should never be passed between threads. Only use a COM object in the
same thread it was created in. Doing otherwise is likely to crash Excel! If you are using a background
thread the safest thing to do is to only call into Excel using COM via functions scheduled
using schedule_call
.
New in PyXLL 5.9
Context manager to disable Excel while performing operations that interact with Excel.
Can only be used from inside an Excel macro, or from a function scheduled using pyxll.schedule_call.
Example:
@xl_macro
def macro_function():
with xl_disable():
# do some work here that updates Excel where we do not
# want Excel to automatically recalculate or update.
xl = xl_app()
xl.Range("A1").Value = 1
# After the with block, Excel reverts to its previous calculation mode.
return
automatic_calculations – Disable automatic calculations until finished.
screen_updating – Disable screen updating until finished.
alerts – Disable alerts until finished.
restore_selection – Restore the current selection when finished.
restore_active_sheet – Restore the current active sheet when finished.
XLCell represents the data and metadata for a cell (or range of cells) in Excel.
XLCell instances are passed as an xl_cell
argument to a function registered with xl_func
, or
may be constructed using from_range
.
Some of the properties of XLCell
instances can only be accessed if the calling function has been registered as a macro sheet
equivalent function [3].
Example usage:
from pyxll import xl_func
@xl_func("xl_cell cell: string", macro=True)
def xl_cell_test(cell):
return "[value=%s, address=%s, formula=%s, note=%s]" % (
cell.value,
cell.address,
cell.formula,
cell.note)
Static method to construct an XLCell from an Excel Range instance or address (e.g. ‘A1’).
The Range class is part of the Excel Object Model, and can be obtained via xl_app
.
See Python as a VBA Replacement.
The XLCell instance returned can be used to get and set values in Excel using PyXLL type converters and object cache.
range – An Excel Range object or cell address as a string.
Example usage:
xl = xl_app()
range = xl.Selection
cell = XLCell.from_range(range)
cell.options(type='object').value = x
Must be called from a macro or macro sheet equivalent function [3]
Get or set the value of the cell.
The type conversion when getting or setting the cell content is determined by the type
passed to XLCell.options
. If no type is specified then the type conversion
will be done using the var
type.
Must be called from a macro or macro sheet equivalent function [3]
String representing the address of the cell, or None
if a value was passed to the function and not a cell reference.
Must be called from a macro or macro sheet equivalent function [3]
Formula of the cell as a string
, or None
if a value was passed to the function and not a cell reference or if the cell has no formula.
Must be called from a macro or macro sheet equivalent function [3]
Note on the cell as a string
, or None
if a value was passed to the function and not a cell reference or if the cell has no note.
Must be called from a macro or macro sheet equivalent function [3]
XLRect
instance with the coordinates of the cell.
True or False indicating whether the cell has been calculated or not. In almost all cases this will always be True as Excel will automatically have recalculated the cell before passing it to the function.
Sets the options on the XLCell instance.
type – Data type to use when converting values to or from Excel. The default
type is var
, but any recognized types may be used, including object
for getting or setting cached objects.
auto_resize –
When setting the cell value in Excel, if auto_resize is set and the value is an array, the cell will be expanded automatically to fit the size of the Python array.
When getting XLCell.value
, if auto_resize is set then the returned value will
also include adjacent cells according to these rules:
If the cell references a table then the entire table’s contents be use used.
Otherwise, if the cell is part of a block of non-blank cells, the values for the entire block are used.
Note: auto_resize was extended to work when getting values in PyXLL 5.8.0. In earlier versions it has no effect when getting the cell value.
type_kwargs – If setting type
, type_kwargs can also be set as the options for that type.
nan_value –
Value to use in the case that the value being set is NaN
.
Defaults to the global setting nan_value
set in the config file, or #NUM!
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
posinf_value –
Value to use in the case that the value being set is +Inf
.
Defaults to the global setting posinf_value
set in the config file, or Excel’s own numeric representation of +Inf
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
neginf_value –
Value to use in the case that the value being set is -Inf
.
Defaults to the global setting neginf_value
set in the config file, or Excel’s own numeric representation of -Inf
if not set.
Set to an Exception instance (e.g. RuntimeError()
) to return an Excel error.
@Since PyXLL 5.5.0
self. The cell options are modified and the same instance is returned, for easier method chaining.
Example usage:
cell.options(type='dataframe', auto_resize=True).value = df
Return an Excel Range COM object using the COM package specified.
com_package – COM package to use to return the COM Range object.
com_package
may be any of:
win32com (default)
comtypes
xlwings
@Since PyXLL 4.4.0
Return a clone of the XLCell
, offset by rows and columns.
rows (int) – Number of rows to offset by.
columns (int) – Number of columns to offset by.
@Since PyXLL 5.8.0
Return a clone of the XLCell
, resized to rows and columns.
rows (int) – Number of rows after resizing (or kept the same if not specified).
columns (int) – Number of columns after resizing (or kept the same if not specified).
@Since PyXLL 5.8.0
XLRect instances are accessed via XLCell.rect
to get the coordinates of the cell.
Footnotes