11
votes

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?

1
I had a good look for you, no luck I'm afraid. - Jeremy Thompson
Is this what you are trying to accomplish but using C# code? support.office.com/en-us/article/… - dmcgill50
Yes, that's what I want to achieve. - Tomtom

1 Answers

0
votes

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?