15

After searching for a while on the internet which produced no success I will ask here.

Some posts in the internet say that it's not possible to apply a digital signature to a VBA-Macro inside an Excel-Application. But all the articles I've found are quite old so I'm hoping that maybe it's now possible to do this by code.

My goal is to open an Excel-Document and apply a digital signature to the vba-macros is this document, assumed that there macros exist.

I have the following code to detect if there are VBMacros in the excel-document:

string filePath = @"E:\OfficeDocuments\Sample1.xlsm";
object isReadonly = true;
object missing = Missing.Value;
_Application application = new Microsoft.Office.Interop.Excel.Application();
workbook = application.Workbooks.Open(
                    filePath, missing, isReadonly, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing,
                    missing, missing, missing);
bool workbookHasVbProject = workbook.HasVBProject;

That just works fine.

Now I grab the certificate which I want to use to sign the macros with:

X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection x509Certificate2Collection = store.Certificates;
X509Certificate2Collection certificate2Collection = x509Certificate2Collection.Find(X509FindType.FindBySubjectName, "MyCertificate 01", true);
if (certificate2Collection.Count > 0)
{
   X509Certificate2 certificate = certificate2Collection[0];
}

And now I have no idea how to continue.

I've tried:

VBE vbe = application.VBE;
VBProject vbProject = vbe.VBProjects.Item(1);

But I don't see any opportunity to sign the macros.

Is there really no way to sign the macros with c#-code?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Tomtom
  • 9,087
  • 7
  • 52
  • 95

2 Answers2

1

It's not C# but there is a way to sign VBA code in Excel files with MS commandline tools. I invoke the related commands from my C# program. Solved Question: Is it possible to sign a Excel VBA project including timestamp?

Rigazoni
  • 209
  • 2
  • 9
0

To sign a VBA Macro you can either do it manually in Tools menu and select Digital Signature or in the VBA code you can use something like this. Create a module and add this

Sub SignMacros() Dim VBComp As VBComponent Set VBComp = ThisWorkbook.VBProject.VBComponents("Module1") VBComp.Sign "YourName", "YourCertificate" End Sub

Change Module1 with the name of your Module you wish to sign, and do the same with YourName and YourCertificate.

ChrisR
  • 81
  • 9