trungn077 > 17-08-14, 11:01 PM
MTNQ > 25-08-14, 03:35 PM
Sub CompactDB(strSourceFile As String, Optional strPassword As String)
On Error GoTo Err_Handler
Dim strFullName As String
Dim strFolderPath As String
Dim strFileName As String
Dim strFileExt As String
Dim strLockExt As String
Dim strBackupFile As String
Dim strCompactFile As String
Dim L As Long
Dim objFSO As Scripting.FileSystemObject
Dim objEngine As DAO.DBEngine
Set objEngine = Application.DBEngine
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFullName = Dir(strSourceFile)
strFolderPath = Left$(strSourceFile, Len(strSourceFile) - Len(strFullName))
L = InStrRev(strFullName, ".")
strFileName = Left$(strFullName, L - 1)
strFileExt = Mid$(strFullName, L)
Select Case strFileExt
Case ".mdb": strLockExt = ".ldb"
Case ".accdb": strLockExt = ".laccdb"
End Select
If Not objFSO.FileExists(strFolderPath & strFileName & strLockExt) Then
strBackupFile = strFolderPath & strFileName & "_Backup" & Format(Date, "yyyymmdd") & strFileExt
strCompactFile = strFolderPath & strFileName & "_COMPACTED" & strFileExt
' Xoa tap tin backup neu no da ton tai
If objFSO.FileExists(strBackupFile) Then
objFSO.DeleteFile strBackupFile
End If
If objFSO.FileExists(strCompactFile) Then
objFSO.DeleteFile strCompactFile
End If
' Sao luu CSDL truoc khi Compact
objFSO.CopyFile strSourceFile, strBackupFile
' Compact CSDL va xuat sang mot tap tin moi (strCompactFile).
If strPassword <> "" Then
objEngine.CompactDatabase strSourceFile, strCompactFile, , , ";pwd=" & strPassword
Else
objEngine.CompactDatabase strSourceFile, strCompactFile
End If
'Neu khong co loi, tuc la qua trinh CompactDatabase hoan thanh thi xoa CSDL hien hanh
objFSO.DeleteFile strSourceFile
'Sua ten file da Compact thanh CSDL hien hanh
objFSO.MoveFile strCompactFile, strSourceFile
'Thong bao da hoan tat qua trinh CompactDatabase
MsgBox "CompactDatabase thanh cong, CSDL truoc thoi diem nen duoc sao luu tai: " & strBackupFile
Else
MsgBox "CSDL dang duoc su dung.Vui long thoat tat ca ung dung dang truy cap den CSDL va thu lai!"
End If
Err_Exit:
Exit Sub
Err_Handler:
MsgBox Err.Description, vbExclamation, "CompactDB Error " & Err.Number
Resume Err_Exit
End Sub
Sub Test()
Dim strs As String
strs = "\\192.168.1.2\Downloads\Database.mdb"
Call CompactDB(strs, "PassWord")
End Sub
ungthienhai > 13-09-22, 09:49 PM
ungthienhai > 13-09-22, 10:03 PM