Workbook.HasMacros is true but VbaProject.Modules is empty

Please see the attached document:
vba.xlsm.zip (11.0 KB)

And the following code:

var workbook = new Workbook("vba.xlsm");
workbook.RemoveMacro();
workbook.Save("out.xlsm");
var workbook2 = new Workbook("out.xlsm");
if (workbook.VbaProject.Modules.Any())
  throw new Exception("Workbook has VBA modules");
if (workbook.HasMacro) 
    throw new Exception("What is going on here?");

I expect no exception to be thrown; however, the 2nd exception is thrown. VbaProject.Modules does not contain any modules.

How is the HasMacro property calculated? Are there other ways an excel document can contain macros that is not covered by VbaProject.Modules? Is it always ‘true’ for xlsm even if there are no actual macros in the file?

Thanks!

  • Uriel

@Buffer2018,

This may be expected behavior. Calling HasMacro can detect the presence of macros. When not present, it returns false. Please note that when you use/call Workbook.VbaProject in code, a default macro will be created, so when you check HasMacro again, it will return true, which is expected. Therefore, if you want to determine whether a workbook has macros or not, just directly call HasMacro. There is no need to call Workbook.VbaProject first, as HasMacro will definitely return true after calling Workbook.VbaProject.

Hope, this helps a bit.

Ah, understood, so simply because I was running it in debugger, the HasMacro property was set to True, because visual studio inspects all properties, therefore the default VBA modules were created.

You can close this ticket, thanks for the fast reply!

@Buffer2018
You are welcome.
If you have any other issue , please feel free to contact us.