Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically enable Excel macro in C#

I have an Excel add-in, and I would like to do the following:

  1. Check if the workbook has any macro.
  2. Prompt user if he wants to enable the macro.
  3. If yes, enable the macro for user.

Is there any way to enable a macro in C#?

like image 316
Dhinnesh Jeevan Avatar asked Aug 05 '26 13:08

Dhinnesh Jeevan


1 Answers

This article is very helpful for you.

According to the article, I implemented this as a WinForm application so I used MessageBox to prompt user if he wants to enable the macro.

Before doing this, you have to check "Trust access to the VBA project object model" at [File]->[Options]->[Trust Center] in your "xlsm" workbook.

using VBA = Microsoft.Vbe.Interop;
using Excel = Microsoft.Office.Interop.Excel;

private void ReadExcel()
{
    string filePath = @"C:\temp\Macro.xlsm";

    Microsoft.Office.Interop.Excel.Application appExcel = null;
    Microsoft.Office.Interop.Excel.Workbooks workbooks = null;
    Microsoft.Office.Interop.Excel.Workbook workbook = null;

    object oMiss = System.Reflection.Missing.Value;

    appExcel = new Microsoft.Office.Interop.Excel.Application();
    appExcel.DisplayAlerts = true;
    appExcel.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityByUI;
    // Make the excel visible
    appExcel.Visible = true;
    workbooks = appExcel.Workbooks;
    workbook = workbooks.Open(filePath, oMiss,
                              oMiss, oMiss,
                              oMiss, oMiss,
                              oMiss, oMiss,
                              oMiss, oMiss,
                              oMiss, oMiss,
                              oMiss, oMiss,
                              oMiss);

    if (workbook.HasVBProject)  // Has macros
    {
        try
        {
            // Show "Microsoft Excel Security Notice" prompt
            var project = workbook.VBProject;
        }
        catch (System.Runtime.InteropServices.COMException comex)
        {
            // Macro is enabled.
        }
    }

    workbook.Close(true, oMiss, oMiss);

    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
    workbook = null;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
    workbooks = null;
    appExcel.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
    appExcel = null;
}
like image 74
jhmt Avatar answered Aug 07 '26 04:08

jhmt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!