检查文件是否已经打开(vba)

可能重复:
检测Excel工作簿是否已经打开(使用VBA)

在这里我find了检查文件是否已经打开的代码

这里是代码:

Function IsFileOpen(FileName As String) Dim iFilenum As Long Dim iErr As Long On Error Resume Next iFilenum = FreeFile() Open FileName For Input Lock Read As #iFilenum Close iFilenum iErr = Err On Error Goto 0 Select Case iErr Case 0: IsFileOpen = False Case 70: IsFileOpen = True Case Else: Error iErr End Select End Function Sub test() If Not IsFileOpen("C:\MyTest\volker2.xls") Then Workbooks.Open "C:\MyTest\volker2.xls" End If End Sub 

但是当我用只读文件进行testing时,这个方法在打开a; ready时返回IsFileOpen = False 。 我该如何解决这个问题?

试试这个,它会抛出

Err.Number = 75如果只读

Err.Number = 70如果打开

并返回不公开的错误

 Option Explicit Function FileLocked(strFileName As String) As Boolean On Error Resume Next ' If the file is already opened by another process, ' and the specified type of access is not allowed, ' the Open operation fails and an error occurs. Open strFileName For Binary Access Read Write Lock Read Write As #1 Close #1 ' If an error occurs, the document is currently open. If Err.Number <> 0 Then ' Display the error number and description. MsgBox "Error #" & Str(Err.Number) & " - " & Err.Description FileLocked = True Err.Clear End If End Function Sub test() Debug.Print FileLocked("C:\Users\ooo\Desktop\test.xlsx") End Sub 

你应该能够解决任何例外的问题。

编辑:是的,我testing它在这里输出时,文件设置为只读

在这里输入图像说明