Introduction
It appears to be difficult to automate the "Compile" and "Make MDE" functions in Access.
Worst practices: The only automated way to Make an MDE is through an undocumented Access SysCmd (ewwww).
Basically, that means this will work for Access 2003, but don't expect it to work in 2007.
Files
The downloaded project will just compile all MDBs in the current directory. (Open it with VS 2005.)
Using the code
Code works:
- For Access 2003
- Using .NET 2.0
References to add:
- Microsoft.Office.Interop.Access (.NET Reference)
- Microsoft DAO 3.6 Object Library (COM Reference)
using System;
using System.IO;
using Microsoft.Office.Interop.Access;
namespace CompileAccessFiles {
public static class AccessDB {
public static FileInfo FullCompileToMDE(FileInfo mdbFile) {
ApplicationClass app = OpenAccessApplication();
CompileVBA(mdbFile, app);
CompactAndRepair(mdbFile, app);
FileInfo newfile = MakeMDE(mdbFile, app);
CloseAccessApplication(ref app);
return newfile;
}
public static void CloseAccessApplication(ref ApplicationClass app) {
app.Quit(AcQuitOption.acQuitSaveNone);
app = null;
}
public static FileInfo MakeMDE(FileInfo mdbFile, ApplicationClass app) {
string newfilename = mdbFile.FullName;
newfilename = newfilename.Remove(newfilename.Length - 1) +
"e";
app.SysCmd((AcSysCmdAction)603, mdbFile.FullName, newfilename);
return new FileInfo(newfilename);
}
public static void CompactAndRepair(FileInfo accessFile, ApplicationClass app) {
string tempFile = Path.Combine(accessFile.Directory.FullName,
Path.GetRandomFileName() + accessFile.Extension);
app.CompactRepair(accessFile.FullName, tempFile, false);
app.Visible = false;
FileInfo temp = new FileInfo(tempFile);
temp.CopyTo(accessFile.FullName, true);
temp.Delete();
}
public static ApplicationClass OpenAccessApplication() {
ApplicationClass app = new ApplicationClass();
app.Visible = false;
return app;
}
public static void CompileVBA(FileInfo mdbFile, ApplicationClass app) {
app.OpenCurrentDatabase(mdbFile.FullName, true, "");
if (!app.IsCompiled) {
app.RunCommand(AcCommand.acCmdCompileAndSaveAllModules);
}
app.CloseCurrentDatabase();
app.Visible = false;
}
}
}