2

In the sample Sample15.cs downloaded from EPPlus, I see that EPPlus can write/inject VBA macros. However, I don't see how to read all the VBA macros from a .xlsm workbook.

Can EPPlus interpret VbaProject.bin and support this functionality?

PS: it seems that Open XML SDK cannot do this either (please correct me if I am wrong), that's why I am considering EPPlus...

SoftTimur
  • 5,630
  • 38
  • 140
  • 292

1 Answers1

1

If you just want to read the code in each modules you just have to go through the 'Workbook.VbaProject.Modules' collection like this:

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("---------");
    }

Which will give you this in the output (I just created an excel xlsm with two modules):

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

---------
Ernie S
  • 13,902
  • 4
  • 52
  • 79
  • That's exactly what I want... Additionally, I am investigating the source code of EEPlus to see how it achieves this... Why don't I see the interpretation of [vbaProject.bin](http://download.microsoft.com/download/2/4/8/24862317-78f0-4c4b-b355-c7b2c1d997db/%5BMS-OVBA%5D.pdf) in *VBA/*.cs`? – SoftTimur Sep 22 '16 at 12:56
  • @SoftTimur I think manipulating the vba bin would be an entire project in itself since it is a binary file. Since vba is kind of a subset/offshoot of the excel DOM it would really need a projects undivided attention to do it justice. If you haven't seen this yet here is a good read: http://www.codeproject.com/Articles/15216/Office-bin-file-format – Ernie S Sep 22 '16 at 13:11
  • But your example shows that EEPlus does read this binary, right? though I don't see which part of its code achieves this... – SoftTimur Sep 22 '16 at 13:22
  • 1
    @SoftTimur That is true, Epplus does manipulate it for its own purposes but I am sure it is only a small fraction of what can be done. But to answer you question, I believe the file `ExcelVbaProject.cs` is does the actual binary reading/writing http://epplus.codeplex.com/SourceControl/latest#EPPlus/VBA/ExcelVBAProject.cs which is referenced in `ExcelWorkbook.cs`. – Ernie S Sep 22 '16 at 13:46