View Full Version : Xem 1 file Excel có đang mở không và đóng lại
vngkhanh
15-08-2008, 16:19
Xin chào các bạn,
Mình đang cần 1 đoạn mã trên Microsoft Access để kiểm tra xem tệp tin "C:\database.xls" có đang mở không, nếu mở thì đóng tệp tin đó lại.
Bạn nào biết cho mình xin đoạn code nhé. Cảm ơn nhiều.
Khanh
huytranaz
15-08-2008, 16:43
Xin chào các bạn,
Mình đang cần 1 đoạn mã trên Microsoft Access để kiểm tra xem tệp tin "C:\database.xls" có đang mở không, nếu mở thì đóng tệp tin đó lại.
Bạn nào biết cho mình xin đoạn code nhé. Cảm ơn nhiều.
Khanh
Bạn thêm 1 trong 2 đoạn code sau vào 1 Module:
1. Dùng Windows API
Option Explicit
'Determine whether a file is already open or not
Private Declare Function lOpen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
Private Declare Function lClose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As Long
'-- Ham kiem tra file dang mo....
Public Function IsFileAlreadyOpen(FileName As String) As Boolean
Dim hFile As Long
Dim lastErr As Long
' Initialize file handle and error variable.
hFile = -1
lastErr = 0
' Open for for read and exclusive sharing.
hFile = lOpen(FileName, &H10)
' If we couldn't open the file, get the last error.
If hFile = -1 Then
lastErr = Err.LastDllError
Else
' Make sure we close the file on success.
lClose (hFile)
End If
' Check for sharing violation error.
IsFileAlreadyOpen = (hFile = -1) And (lastErr = 32)
End Function
2. Không dùng Windows API (Code tham khảo: http://support.microsoft.com/kb/213383)
Option Explicit
Public Function IsFileAlreadyOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileAlreadyOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileAlreadyOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
Chúc vui,
vngkhanh
19-08-2008, 13:36
Cảm ơn bạn Huy đã cho xin code, mình chạy thử thấy rất ổn. NHưng đoạn code này chỉ phát hiện xem file có đang mở không thôi, không đóng file nếu file đang mở.
Có bạn nào có code không cho mình xin với,
Cảm ơn nhiều.
Em cũng đang gặp trường hợp tuơng tự. Em kiểm tra được file đang mở nhưng không biết làm cách nào để đóng nó. Rất mong các anh chị giúp đỡ hướng dẫn em làm. Cám ơn các anh chị.
Powered by vBulletin® Version 4.2.0 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.