Search code examples
c#excelxlsmspire.xls

Spire.xls is deleting all macros


I have an xlsm file (Excel with macros).
I open it in C# with Spire.xls, make changes, save it. Now all the VBA, modules, classes, and code behind the forms are gone.
Spire doesn't do anything with macros, but I had hoped that it would at least preserve what was already there.

I have VBA code for importing macros, but doesn't work for class modules.
I think I could rewrite that to operate on another workbook if I had to.

But I'm hoping for something I can use directly from C#.

It doesn't matter if I copy the file first and then just use spire to save it or use spire's SaveToFile.
Sample code:

     File.Copy(sourceFileName, targetFileName);
     // Load the base worksheet
     Workbook baseWorkbook.LoadFromFile(targetFileName);
     /* or */ Workbook baseWorkbook.LoadFromFile(sourceFileName);

     // do some stuff with the workbook

     baseWorkbook.Save();
     /* or */ baseWorkbook.SaveToFile(targetFileName, FileFormat.Version2016);

Either way, I end up with a file with 0 code.

Alternatively, I could convert it to use Interop.Excel, but that can't copy merged cells.


Solution

  • The file will be saved as a .xlsx file if you specify the file format as FileFormat.Version2016. To maintain macros, you can save the file to a .xlsm file by specifying the file format as FileFormat.Xlsm.