A bit of Excel heresy: the LAMBDA()
function is great. But rather than write my own, really complex function to perform a task, I’d rather borrow from an established Python function.
The xlwings
Excel add-in is useful for just these types of scenarios, but it takes a bit of effort to set up. If you have not already installed the add-in, check out this post.
Creating your first project
By its nature as a tool to integrate Python and Excel, the xlwings
add-in takes a few layers to get up and running. I’d suggest starting with xlwings
‘s own demo file. Get started with this by opening Anaconda Prompt on your computer.
At the blinking cursor, type xlwings quickstart first_udf
and hit Enter. If successful, you should see an xlwings
version number returned like so:
Open your file explorer and you should now see a first_udf
folder created in this directory. You can always change these names later, but for now let’s take a look at completing setup.
Configuring the add-in
You are getting close to writing Python functions from Excel! There’s just a bit more to set up. Open the first_udf.xlsm
file in your first_udf
folder and head to the xlwings tab. Time to check two things:
PYTHONPATH
Go to the first group in the tab, called Python. Inside PYTHONPATH, place the folder path that leads to your first_udf.py
file. Do not include the first_udf.py
file itself; just the folder.
In the case of our example, the PYTHONPATH will be
C:\Users\GeorgeMount\first_udf
UDF Modules
The other field to complete is UDF Modules in the User Defined Functions (UDFs) group of the xlwings ribbon. Make sure this is set exactly to the name of your .py
file in this folder, but do not include .py
in the name. In our case, that would be
first_udf
Your xlwings ribbon should now look something like this:
Testing your setup
Congratulations! At this point, you should be ready to call user-defined functions from Python, right from Excel.
To confirm, be sure to click on Import Functions from the User Defined Functions (UDFs) group and try the following, built-in hello()
function:
A hello()
function is ready to use that takes an Excel input, conduct the processes, and return the result back into Excel. To learn more about how this works and how to write your own functions, check out future posts in this series.
What questions do you have about xlwings
, the package’s add-in or about Excel with Python in general? Let me know in the comments.
Leave a Reply