0

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.

BWhite
  • 713
  • 1
  • 7
  • 24
  • 1
    Is it being saved as .xlsm ? – Solar Mike Apr 01 '23 at 04:24
  • @SolarMike Yes, both the source and target files are xlsm. But, interestingly, if you try to open it, if throws an exception since it doesn't actually have any macros in it. Changing the extension to xlsx lets you open it. – BWhite Apr 02 '23 at 05:05
  • 1
    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**. – Dheeraj Malik Apr 03 '23 at 09:02
  • @DheerajMalik That fixed it. Can you convert this into an answer so I can accept it? Note that if you save the file again later, it will still delete the macros. You can only do SaveAsFile. – BWhite Apr 05 '23 at 19:53
  • @BWhite Thanks, I posted it as an answer. When saving files, I recommend you always use the SaveToFile() method, even if it's saved to the same file. – Dheeraj Malik Apr 07 '23 at 10:18

1 Answers1

1

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.

Dheeraj Malik
  • 703
  • 1
  • 4
  • 8