Writing User Defined Functions (UDFs)
Enter search terms or a module, class or function name.
New menu items can be added to the PyXLL Excel Addin menu easily by using the xl_menu decorator.
xl_menu is a function that returns a decorator for creating menu items that call Python functions.
| Parameters: |
|
|---|
To add a new menu entry to the PyXLL menu you use the xl_menu decorator with the label you want to use for that menu item, and a function that takes no arguments that will be called when that menu item is selected.
Here is an example of a simple menu item that uses win32api to display a message box to the user:
from pyxll import xl_menu
import win32api
@xl_menu("My menu item")
def my_menu_item():
win32api.MessageBox(0, "Hello from PyXLL", "Menu button example")
Menu items may modify the current workbook, or in fact do anything that you can do via the Excel automatition API. This allows you to do anything in Python that you previously would have had to have done in VBA.
Below is an example that uses the win32com module to call back into Excel from a menu item:
from pyxll import xl_menu, get_active_object
import win32com.client
@xl_menu("win32com menu item")
def win32com_menu_item():
# get the Excel application object
xl_window = get_active_object()
xl_app = win32com.client.Dispatch(xl_window).Application
# get the current selected range
selection = xl.Selection
# set some text to the selection
selection.Value = "Hello!"
As well as adding menu items to the main PyXLL addin menu it’s possible to create entirely new menus.
To create a new menu, use the menu keyword argument to the xl_menu decorator.
In addition, if you want to control the order in which menus are added you may use the menu_order integer keyword argument. The higher the value, the later in the ordering the menu will be added.
Below is a modification of an earlier menu example that puts the menu item in a new menu, called “New Menu”:
from pyxll import xl_menu
import win32api
@xl_menu("My menu item", menu="New Menu")
def my_menu_item():
win32api.MessageBox(0, "Hello from PyXLL", "new menu example")
Sub-menus may also be created. To add an item to a sub-menu, use the sub_menu keyword argument to the xl_menu decorator.
All sub-menu items share the same sub_menu argument. The ordering of the items within the submenu is controlled by the sub_order integer keyword argument. In the case of sub-menus, the order keyword argument controls the order of the sub-menu within the parent menu.
For example, to add the sub-menu item “TEST” to the sub-menu “Sub Menu” of the main menu “My Menu”, you would use a decorator as illustrated by the following code:
from pyxll import xl_menu
import win32api
@xl_menu("TEST", menu="My Menu", sub_menu="Sub Menu")
def my_submenu_item():
win32api.MessageBox(0, "Hello from PyXLL", "sub menu example")
