Embedded Code

xlwings PRO allows you to store your Python code directly in Excel so you don’t have to distribute separate Python files.

All you have to do is:

  • Name a sheet with a .py ending (can also be a hidden or very hidden sheet)

  • Copy/paste your Python source code

Note

Make sure to select Paste Special > Text as you might otherwise get errors with indentation or unrecognized characters.

Then, use the VBA function RunPython ("import mymodule;mymodule.myfunction()") as usual.

Note that you can have multiple Excel sheets and import them like normal Python files. Consider this example:

../_images/embedded_code1.png
../_images/embedded_code2.png

You can call this function from VBA like so:

Sub RandomNumbers()
    RunPython ("import random_numbers;random_numbers.main()")
End Sub

Note

UDFs modules don’t have to be added to the UDF Modules explicitly when using embedded code. However, in contrast to how it works with external files, you currently need to re-import the functions when you change them.

Note

While you can hide your sheets with your code, they will be written to a temporary directory in clear text.