通过 EPPlus 获取工作簿的所有 VBA 宏

Get all the VBA macros of a workbook by EPPlus

在从 EPPlus 下载的示例 Sample15.cs 中,我看到 EPPlus 可以 write/inject VBA 宏。但是,我看不到如何从 .xlsm 工作簿中读取所有 VBA 宏。

EPPlus 可以解释 VbaProject.bin 并支持此功能吗?

PS:好像Open XML SDK也做不到(如果我错了请指正),这就是我考虑EPPlus的原因...

如果您只想阅读每个模块中的代码,您只需像这样浏览 'Workbook.VbaProject.Modules' 集合:

var fi = new FileInfo(@"C:\temp\Book1.xlsm");
using (var pck = new ExcelPackage(fi))
{
    var modules = pck.Workbook.VbaProject.Modules;
    foreach (var module in modules)
    {
        Console.WriteLine($"Module Name: {module.Name}{Environment.NewLine}Code:");
        Console.Write(module.Code);
        Console.WriteLine("---------");
    }

这将在输出中给你这个(我刚刚创建了一个带有两个模块的 excel xlsm):

Module Name: ThisWorkbook
Code:
---------
Module Name: Sheet1
Code:
---------
Module Name: Module1
Code:
Public Sub proc1()
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim ws As Worksheet
    Set ws = wb.ActiveSheet

    ws.Cells(1, 1).Value = "proc1"

End Sub

---------
Module Name: Module2
Code:
Public Sub proc2()
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim ws As Worksheet
    Set ws = wb.ActiveSheet

    ws.Cells(2, 1).Value = "proc2"

End Sub

---------