hegdep
hegdep

Reputation: 596

How do I assign an xlwings function to a button

When I create a module under xlwings to call a Python script, how do I assign it to a button on excel?

Trying to assign a macros to a button seems to only provide options of functions in the main workbook.

Upvotes: 0

Views: 3570

Answers (3)

Tony Roberts
Tony Roberts

Reputation: 417

To write Excel macros in Python that are available for all workbooks, you can use PyXLL.

See the following link to the docs for details of how to expose Python functions as macros and call them from Excel.

https://www.pyxll.com/docs/userguide/macros.html#calling-macros-from-excel

Upvotes: 0

James Carter
James Carter

Reputation: 833

After adding the excel add-in to VBA, insert a new module (insert->module) and write the following code. Then, create a button under the developer tab, right click on the button, and click assign macro. Then find the macro you wrote called Button.

Sub Button()
    RunPython("import filename")
End Sub

Upvotes: 0

jcrizk
jcrizk

Reputation: 615

I don't think you can assign a Python script to an Excel button, but I think a solution could be to assign VBA code to the button's click event that calls the Python script.

To do this:

  1. Go to the Developer tab (Developer tab?!) -> Click 'Visual Basic'

  2. At the top, select 'Insert' -> 'Module'

  3. Create a Public Sub MySubName() in the module that calls the Python script.

  4. Right click the button you want to assign the Sub to -> "Assign Macro..." -> choose the Sub's name.

And that should be it, assuming you know how to call Python from VBA.

Upvotes: 1

Related Questions