nguyendang95
Thành viên thường trực




- Tham gia
- 25/5/22
- Bài viết
- 206
- Được thích
- 179
Thường thì trong VBA có nhiều cách để kiểm tra sự tồn tại của tập tin:
Bằng thư viện COM, ví dụ:
Ví dụ, để kiểm tra xem tập tin với đường dẫn Y:\dstockbot.xlsb có đang tồn tại hay không.
Tham khảo bài viết của Raymond Chen, một trong những kiến trúc sư đời đầu của hệ điều hành Windows.
Superstition: Why is GetFileAttributes the way old-timers test file existence?
Bằng thư viện COM, ví dụ:
- FileSystemObject
- ...
- CreateFile
- FindFirstFile
- PathFileExists (Shlwapi)
- ...
Mã:
Private Const INVALID_FILE_ATTRIBUTES = -1
Private Const FILE_ATTRIBUTE_DIRECTORY = &H10
Private Declare PtrSafe Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesW" (ByVal lpFileName As LongPtr) As Long
Private Function FileExists(ByVal Path As String) As Boolean
If (Path = vbNullString) Then
FileExists = False
Exit Function
End If
Dim lngAttr As Long
lngAttr = GetFileAttributes(StrPtr(Path))
FileExists = (lngAttr <> INVALID_FILE_ATTRIBUTES And Not (lngAttr = FILE_ATTRIBUTE_DIRECTORY))
End Function
Ví dụ, để kiểm tra xem tập tin với đường dẫn Y:\dstockbot.xlsb có đang tồn tại hay không.
Mã:
Private Sub Test()
Const strPath As String = "Y:\dstockbot.xlsb"
Dim strAnswer As String
strAnswer = IIf(FileExists(strPath), strPath & " exists", strPath & " does not exist")
Debug.Print strAnswer
End Sub
Tham khảo bài viết của Raymond Chen, một trong những kiến trúc sư đời đầu của hệ điều hành Windows.
Superstition: Why is GetFileAttributes the way old-timers test file existence?


