python 执行vba脚本,使用Python编写VBA脚本?

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.

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.

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.

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

解决方案

Yes, it is possible. You can start looking at how you can generate a VBA macro from VB on that Microsoft KB.

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:

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值