如何以编程方式查看旧Access数据库的VBA代码



为了便于迁移到Windows 10和Office 365环境,我需要编写一个程序(用C#或VB.NET编写(,该程序将读取旧Access数据库(2003年以后的任何数据库(的VBA代码,并查找特定的代码片段,如果可能,请更改代码并保存。这需要在大约500个Access数据库上执行。

我以前在Word和Excel中做过这件事,没有遇到太多麻烦,但我似乎无法将其用于Access。

我试过这样:

var appClass = new Microsoft.Office.Interop.Access.Application();
appClass.OpenCurrentDatabase(thefilepath, false, "");
var dbs = appClass.CurrentProject;
foreach (AccessObject myMods in dbs.AllModules)
{
//Look at the module here and look at the code
}

像这样:

accessApp = new Microsoft.Office.Interop.Access.ApplicationClass();
accessApp.OpenCurrentDatabase(inputMdb, false, password);
foreach (Access.AccessObject obj in accessApp.CurrentProject.AllModules)
{
//Look at the module here and look at the code
}

但我会遇到这样的错误:

System.Runtime.InteropServices.COMException:'您输入的是一个已关闭或不存在的对象

就我的一生而言,我无法让这件事发挥作用,任何帮助都将不胜感激。

我不确定AccessObject,也不确定它是否适用于其他MS Office程序,但我过去访问模块的方式是通过VBProject.VBComponents

以下内容应该有效:

using Microsoft.Vbe.Interop;
using MSAccess = Microsoft.Office.Interop.Access;
//...
var accessApp = new MSAccess.Application();
accessApp.OpenCurrentDatabase(inputMdb, false, password);
foreach (VBComponent vbc in accessApp.VBE.ActiveVBProject.VBComponents)
{
var module = vbc.CodeModule;
// To print all code in the file:
Console.WriteLine(module.Lines[1, module.CountOfLines]);
// To export to file:
vbc.Export(somePath);
// To insert code:
module.InsertLines(4, newLineOfCode);
// To replace code:
module.ReplaceLine(5, modifiedLineOfCode);
}
accessApp.CloseCurrentDatabase();
accessApp.Quit();

最新更新