以编程方式在C#中启用Excel宏

时间:2015-10-15 02:04:23

标签: c# excel

我有一个Excel加载项,我想执行以下操作:

  1. 检查工作簿是否有宏。
  2. 提示用户是否要启用宏。
  3. 如果是,请为用户启用宏。
  4. 有没有办法在C#中启用宏?

1 个答案:

答案 0 :(得分:3)

This article对您非常有帮助。

根据文章,我将其实现为WinForm应用程序,因此我使用MessageBox来提示用户是否要启用宏。

在此之前,您必须检查"信任对VBA项目对象模型的访问权限"在[文件] - > [选项] - > [信任中心]在您的" xlsm"工作簿。

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;
}