检查文件是否已打开(vba) [英] Check If a File Is Already Open (vba)

查看:3465
本文介绍了检查文件是否已打开(vba)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

这里我发现代码检查文件是否已经打开

Here I found code that checks if file is already open

这是代码:

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 

但是当我使用只读文件测试时,此方法返回 IsFileOpen = False 当它打开一个;准备好了如何解决这个问题?

But when I test with a read only file this method returns IsFileOpen = False when it was opened a;ready. How can I resolve this?

推荐答案

尝试这样做会抛出

Err.Number = 75如果只读

Err.Number = 75 if readonly

Err.Number = 70如果打开

Err.Number = 70 if open

并返回false没有打开

and return false of not open

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

你应该能够围绕任何例外进行编码。

you should be able to code your way around any exceptions.

编辑:是的,我测试这里是文件设置为读取时的输出只有

Yes I tested it here is output when file is set to read only

这篇关于检查文件是否已打开(vba)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆