如何将 VBA 代码从 de 模块导出到文本?

How can I export VBA code to text from de modules?

我正在尝试映射我在办公室的某些 excel 中的所有 VBA 代码。

在我的工作中,我们有两百多个 excel 文件,每个文件中都有很多宏。如何提取某个模块的代码文本?

我见过类似的东西

workbook = excel.Workbooks.Open("{}{}.xlsm".format(path, file), True, True)
for i in workbook.VBProject.VBComponents:
    print(i.Name)

Return

Plan1
Plan2
Main
Plan5
Plan3
Plan4
Sheet1

如何获取这些模块中的 VBA 代码?

解决方案可能在 VBA 或 Python

也许这接近您要找的东西?

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

这将循环遍历您的 VBAProject(存储此宏本身的位置),并将模块保存在一个 .bas 文件中,您可以打开并浏览该文件。

编辑:您可以将 .bas 替换为 .txt 并且有效,仅供参考。

我找到了解决方案:

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 带有模块名称,如 table 的头部。 查看我找到的每个文本

# To get the full text
module_name = df["module_name"][0]
#To get by line
module_text_by_line = module_name.splitlines()

感谢帮助我的人。