我正在尝试映射我在办公室中某些excel中的所有VBA代码。
在我的工作中,我们有200多个excel文件,每个文件中都有很多宏。如何提取某些模块的代码文本?
我看到了类似的东西
workbook = excel.Workbooks.Open("{}{}.xlsm".format(path, file), True, True)
for i in workbook.VBProject.VBComponents:
print(i.Name)
返回
Plan1
Plan2
Main
Plan5
Plan3
Plan4
Sheet1
如何在这些模块中获取VBA代码?
该解决方案可以使用VBA或Python
答案 0 :(得分:0)
也许这与您要寻找的东西很接近?
nullptr
这将循环遍历VBAProject(此宏本身存储在其中),并将模块保存在Sub GEN_USE_Export_all_modules_from_Project()
' https://www.ozgrid.com/forum/forum/help-forums/excel-general/60787-export-all-modules-in-current-project
' reference to extensibility library
Dim tday As String
tday = Date
Dim objMyProj As VBProject
Dim objVBComp As VBComponent
Dim destFolder as String
destFolder = "C:\Users\WHATEVER\Documents\Business\EXCEL NOTES\"
Set objMyProj = Application.VBE.ActiveVBProject
tday = WorksheetFunction.Substitute(tday, "/", "-")
For Each objVBComp In objMyProj.VBComponents
If objVBComp.Type = vbext_ct_StdModule Then
objVBComp.Export destFolder & tday & " - " & objVBComp.name & ".bas"
End If
Next
MsgBox ("Saved to " & destFolder)
End Sub
文件中,您可以打开并浏览该文件。
编辑:您可以将.bas
替换为.bas
,仅供参考。
答案 1 :(得分:0)
我找到了解决方法:
import win32com.client
import pandas as pd
excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.Workbooks.Open("{}{}.xlsm".format(path, file), True, True)
dict_modules = {}
for i in workbook.VBProject.VBComponents:
name = i.name
lines = workbook.VBProject.VBComponents(name).CodeModule.CountOfLines
# To jump empty modules
if lines == 0:
pass
else:
text = workbook.VBProject.VBComponents(name).CodeModule.Lines(1,lines)
dict_modules[name] = [text]
df = pd.DataFrame(dict_modules)
返回DataFrame时,其模块名称类似于表的开头。 要查看我找到的每个文本
# To get the full text
module_name = df["module_name"][0]
#To get by line
module_text_by_line = module_name.splitlines()
感谢尝试帮助我的人。