且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将用户定义的函数添加到Visual Studio Excel加载项

更新时间:2023-12-06 13:08:10

可以创建模块。但是,为了使其工作,必须在Excel中选择信任对VB项目模型的访问设置。如果未选择信任设置,则会抛出访问被拒绝的错误。

It is possible to create the module. However for this to work the setting to "Trust access to the VB Project model" must be selected in Excel. It throws an error that access is denied if the trust setting is not selected.

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

Excel.Application eApp = new Excel.Application();

eApp.Visible = true;
Excel.Workbook eBook = eApp.Workbooks.Add();

VB.VBProject eVBProj = (VB.VBProject)eBook.VBProject;
VB._VBComponent vbModule = eVBProj.VBE.ActiveVBProject.VBComponents.Add(VB.vbext_ComponentType.vbext_ct_StdModule);

String functionText = "Function MyTest()\n";
      functionText += "MsgBox \"Hello World\"\n";
      functionText += "End Function";

vbModule.CodeModule.AddFromString(functionText);