使用Python从Excel电子表格中读取VBA [英] Using Python to read VBA from an Excel spreadsheet

查看:213
本文介绍了使用Python从Excel电子表格中读取VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用(最好是)Python编写一个VBA差异程序.是否有Python库可以让我阅读Excel电子表格中包含的VBA?

I would like to write a VBA diff program in (preferably) Python. Is there a Python library that will allow me to read the VBA contained in an Excel spreadsheet?

推荐答案

下面是一些快速而肮脏的样板,可以帮助您入门.它使用Excel COM对象(仅Windows解决方案):

Here's some quick and dirty boilerplate to get you started. It uses the Excel COM object (a Windows only solution):

from win32com.client import Dispatch
wbpath = 'C:\\example.xlsm'
xl = Dispatch("Excel.Application")
xl.Visible = 1
wb = xl.Workbooks.Open(wbpath)
vbcode = wb.VBProject.VBComponents(1).CodeModule
print vbcode.Lines(1, vbcode.CountOfLines)

这会打印出我为该示例记录的傻宏:

This prints the silly macro I recorded for this example:

Sub silly_macro()
'
' silly_macro Macro
'

'
    Range("B2").Select
End Sub

请注意,LinesVBComponents使用基于1的索引. VBComponents还支持按模块名称进行索引.另外请注意,Excel在路径中需要反斜杠.

Note that Lines and VBComponents use 1-based indexing. VBComponents also supports indexing by module name. Also note that Excel requires backslashes in paths.

要深入研究,请参阅Pearson的对VBA编辑器进行编程. (以上示例是我从那里浏览的内容拼凑而成的.)

To dive deeper see Pearson's Programming The VBA Editor. (The above example was cobbled together from what I skimmed from there.)

这篇关于使用Python从Excel电子表格中读取VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆