使用 Python 编写 VBA 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19505676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Python to Write VBA Script?
提问by Mike
This might be a bit of a stretch, but is there a possibility that a python script can be used to create VBA in MS Excel (or any other MS Office product that uses VBA) using pythonwin or any other module.
这可能有点牵强,但是否有可能使用 python 脚本在 MS Excel(或任何其他使用 VBA 的 MS Office 产品)中使用 pythonwin 或任何其他模块创建 VBA。
Where this idea came from was pythons openpyxl modules inability to do column autowidth. The script I have creates a workbook in memory and eventually saves it to disc. There are quite a few sheets and within each sheet, there are quite a few columns. I got to thinking....what if I just use python to import a VBA script (saved somewhere in notepad or something) into the VBA editor in excel and then run that script from python using pythonwin.
这个想法的来源是 python openpyxl 模块无法执行列自动宽度。我的脚本在内存中创建了一个工作簿,并最终将其保存到光盘中。有相当多的工作表,每张工作表中都有相当多的列。我开始思考......如果我只是使用 python 将 VBA 脚本(保存在记事本或其他地方)导入到 Excel 中的 VBA 编辑器,然后使用 pythonwin 从 python 运行该脚本会怎样。
Something like:
就像是:
Workbooks.worksheets.Columns("A:Z").EntireColumn.Autofit
Before you comment, yes I have seen lots of pythonic examples of how to work around auto adjusting columns in openpyxl, but I see some interesting opportunities that can be had utilizing the functionality you get from VBA that may not be available in python.
在您发表评论之前,是的,我已经看到了很多关于如何在 openpyxl 中解决自动调整列的 Python 示例,但是我看到了一些有趣的机会,可以利用您从 VBA 获得的功能可能在 Python 中不可用。
Anyways, I dug around the internet a bit and I didn't see anything that indicates i can, so i thought I'd ask.
无论如何,我在互联网上搜索了一下,没有看到任何表明我可以的东西,所以我想我会问。
Cheers, Mike
干杯,迈克
回答by Boud
Yes, it is possible. You can start looking at how you can generate a VBA macro from VB on that Microsoft KB.
对的,这是可能的。您可以开始研究如何从Microsoft KB上的 VB 生成 VBA 宏。
The Python code below is illustrating how you can do the same ; it is a basic port of the first half of the KB sample code:
下面的 Python 代码说明了如何做同样的事情;它是KB示例代码前半部分的基本移植:
import win32com.client as win32
import comtypes, comtypes.client
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xlmodule = ss.VBProject.VBComponents.Add(1) # vbext_ct_StdModule
sCode = '''sub VBAMacro()
msgbox "VBA Macro called"
end sub'''
xlmodule.CodeModule.AddFromString(sCode)
You can look at the visible automated Excel macros, and you will see the VBAMacro
defined above.
您可以查看可见的自动化 Excel 宏,您将看到VBAMacro
上面定义的。