我正在尝试查找目录中的所有Access数据库,并且每次都打开Compact而修复每个数据库而不打开Access。我发现以下文章解释了如何找到它们并写入文件: Batch file to find all Access Databases,但理想情况下,我想在不写入文件的情况下找到它们并进行压缩。
我已经搜索了如何调用/compact
命令行功能,但我不知道如何在我找到的数据库上执行此操作。是否可以编写.bat
文件来执行此操作?类似的东西:
@echo off
"C:\Program Files\Microsoft Office\Office14\MSACCESS.EXE"
"C:\Databases\ /s" *.accdb
/compact
非常感谢任何语法帮助。
答案 0 :(得分:3)
考虑使用Access'专用的CompactRepair方法,您可以在VBA中运行(在Access数据库内部或外部,如在Excel宏中)。需要注意的是Compact&修复实际上会创建现有数据库的副本并将其替换为原始数据库,因此需要进行一些文件处理。
VBA (在MSAccess.exe内)
Sub RunCompactDBs()
Dim path As String
Dim accfile As Variant
path = "C:\Databases\"
accfile = Dir(path & "*.accdb", vbDirectory)
Do While Len(accfile) > 0
bkfile = Replace(accfile, ".accdb", "_bk.accdb")
' CREATE COMPACTED BACKUP
Application.CompactRepair path & accfile, path & bkfile, False
' COPY TO ORIGINAL PATH
FileCopy path & bkfile, path & accfile
' DESTROY COMPACTED BACKUP
Kill path & bkfile
accfile = Dir
Loop
Set accApp = Nothing
End Sub
VBA (在MSAccess.exe之外)
Sub RunCompactDBs()
Dim path As String
Dim accfile As Variant
Dim accApp As Object
Set accApp = CreateObject("Access.Application")
path = "C:\Databases\"
accfile = Dir(path & "*.accdb", vbDirectory)
Do While Len(accfile) > 0
bkfile = Replace(accfile, ".accdb", "_bk.accdb")
accApp.CompactRepair path & accfile, path & bkfile, False
FileCopy path & bkfile, path & accfile
Kill path & bkfile
accfile = Dir
Loop
Set accApp = Nothing
End Sub
并且没有理由坚持使用VBA。任何可以构成Access对象库的COM接口的语言都可以像开源语言那样运行压缩和修复过程:
<强>的Python 强>
import os, glob, shutil
import win32com.client
# LAUNCH ACCESS APP
oApp = win32com.client.Dispatch("Access.Application")
for file in glob.glob("C:\\Databases\\*.accdb"):
bkfile = file.replace(".accdb", "_bk.accdb")
oApp.CompactRepair(file, bkfile, False)
shutil.copyfile(bkfile, file)
os.remove(bkfile)
oApp = None
<强> - [R 强>
library(RDCOMClient)
# LAUNCH ACCESS APP
oApp = COMCreate("Access.Application")
accfiles <- list.files(path="C:\\Databases\\", pattern="\\.accdb", full.names=TRUE)
for (file in accfiles){
bkfile = sub(".accdb", "_bk.accdb", file)
oApp$CompactRepair(file, bkfile, FALSE)
file.copy(bkfile, file, overwrite = TRUE)
file.remove(bkfile)
}
oApp <- NULL
gc()
<强> PHP 强>
# LAUNCH ACCESS APP
$acc = new COM("Access.Application", NULL, CP_UTF8) or Die ("Did not instantiate Access");
foreach (glob("C:\\Databases\\*.accdb") as $file) {
$bkfile = str_replace(".accdb", "_bk.accdb", $file);
$acc->Application->CompactRepair($file, $bkfile, false);
copy($bkfile, $file);
unlink($bkfile);
}
$acc = NULL;
unset($acc);