Xử lý file và thư mục trong VBA

Hướng dẫn chi tiết cách xử lý file và thư mục trong VBA, qua các bài ví dụ thực hành làm phần mềm thực tế bằng MS Access

  1. Khai báo FileSystemObject
  2. Các thao tác với File
  3. Các thao tác với Folder
  4. Lặp qua tất cả các file trong một thư mục
  5. Ví dụ hoàn chỉnh – Sao lưu file Access

Trong VBA trong Access, bạn có thể xử lý file và thư mục (copy, xóa, tạo, kiểm tra tồn tại...) bằng cách kết hợp các hàm nội bộ và thư viện Scripting.FileSystemObject. Dưới đây là hướng dẫn đầy đủ:

1. Khai báo FileSystemObject

Để xử lý file nâng cao, bạn nên sử dụng Scripting.FileSystemObject.
👉 Cách khai báo:

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

2. Các thao tác với File

🔹 Kiểm tra file có tồn tại:

If fso.FileExists("C:\Data\myfile.txt") Then
    MsgBox "File tồn tại!"
End If


🔹 Copy file:

fso.CopyFile "C:\Data\myfile.txt", "D:\Backup\myfile.txt", True  'True để ghi đè nếu file đích tồn tại

🔹 Xóa file:

fso.DeleteFile "C:\Data\myfile.txt", True  'True để không hiển thị hộp thoại xác nhận

3. Các thao tác với Folder

🔹 Kiểm tra folder có tồn tại:

If fso.FolderExists("C:\Data") Then
    MsgBox "Folder tồn tại!"
End If


🔹 Tạo folder mới:

If Not fso.FolderExists("C:\NewFolder") Then
    fso.CreateFolder "C:\NewFolder"
End If


🔹 Copy folder:

fso.CopyFolder "C:\SourceFolder", "D:\BackupFolder", True

🔹 Xóa folder:

fso.DeleteFolder "C:\OldFolder", True

4. Lặp qua tất cả các file trong một thư mục

Dim folder As Object
Dim file As Object

Set folder = fso.GetFolder("C:\Data")

For Each file In folder.Files
    Debug.Print file.Name
Next

5. Ví dụ hoàn chỉnh – Sao lưu file Access

Sub BackupAccessFile()
    Dim fso As Object
    Dim sourceFile As String, backupFile As String

    sourceFile = "C:\Data\MyApp.accdb"
    backupFile = "D:\Backup\MyApp_Backup.accdb"

    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists(sourceFile) Then
        fso.CopyFile sourceFile, backupFile, True
        MsgBox "Đã sao lưu thành công!"
    Else
        MsgBox "Không tìm thấy file nguồn!"
    End If
End Sub

Tìm kiếm:

Bài viết liên quan:

Hướng dẫn chi tiết cách xử lý file và thư mục trong VBA, qua các bài ví dụ thực hành làm phần mềm thực tế bằng MS Access