Create a macro for Microsoft Access via Interop

时间秒杀一切 提交于 2019-12-01 09:36:41

Taken from answers.microsoft.com:

A macro in Access is a special database object, unlike in other Office applications where a macro is simply a VBA procedure without arguments. As far as I know you can't create an Access macro programmatically. -HansV MVP (April 27, 2011)

There is another answer posted at the same question that says you can create new code/VBA objects using the VB Extensibility Library.

Because of HK1's answer, I was able to do exactly what I needed. I wanted to post my code because there is little to no information anywhere on how to do this. I will leave HK1's post marked as the answer because he is what lead me to this.

Programmatically adding VB Modules to MS-Access via Interop

try
{
    Microsoft.Office.Interop.Access.Application accessApp = new Microsoft.Office.Interop.Access.Application();
    accessApp.Visible = true;

    accessApp.OpenCurrentDatabase(filePath);

    // Get the active VBProject item
    VBProject project = accessApp.VBE.VBProjects.Item(1);

    VBComponent module = project.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);

    module.CodeModule.AddFromString(script);
}
catch (Exception ex)
{
    // Trust or the VBA Project Module has not been enabled.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!