我有一个Excel加载项,我想执行以下操作:
有没有办法在C#中启用宏?
答案 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;
}