简体   繁体   English

如何将xlwings函数分配给按钮

[英]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? 当我在xlwings下创建一个模块来调用Python脚本时,如何将其分配给excel上的按钮?

Trying to assign a macros to a button seems to only provide options of functions in the main workbook. 尝试将宏分配给按钮似乎仅在主工作簿中提供功能选项。

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. 我认为您无法将Python脚本分配给Excel按钮,但我认为解决方案可能是将VBA代码分配给调用Python脚本的按钮的click事件。

To do this: 去做这个:

  1. Go to the Developer tab ( Developer tab?! ) -> Click 'Visual Basic' 转到“开发人员”选项卡(“ 开发人员”选项卡?! )->单击“ Visual Basic”

  2. At the top, select 'Insert' -> 'Module' 在顶部,选择“插入”->“模块”

  3. Create a Public Sub MySubName() in the module that calls the Python script. 在调用Python脚本的模块中创建Public Sub MySubName()

  4. Right click the button you want to assign the Sub to -> "Assign Macro..." -> choose the Sub 's name. 右键单击您想要将Sub分配给->“ Assign Macro ...”->选择Sub的名称的按钮。

And that should be it, assuming you know how to call Python from VBA. 假设您知道如何从VBA调用Python,就是这样。

After adding the excel add-in to VBA, insert a new module (insert->module) and write the following code. 将excel加载项添加到VBA之后,插入一个新模块(插入->模块)并编写以下代码。 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. 然后找到您编写的名为Button的宏。

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

To write Excel macros in Python that are available for all workbooks, you can use PyXLL. 要在Python中编写可用于所有工作簿的Excel宏,可以使用PyXLL。

See the following link to the docs for details of how to expose Python functions as macros and call them from Excel. 有关如何将Python函数公开为宏并从Excel调用它们的详细信息,请参见以下文档链接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM