检测Excel工作簿是否已经打开
问题描述:
我已经通过编码打开了名为myWork.XL的MS Excel文件。现在我想要一个可以告诉我它的状态的代码 - 无论是否开放。换句话说,如果我打开相同的文件,它应该告诉我该文件已经打开。
I have opened a file of MS Excel named as "myWork.XL" through coding. Now I want a code that can tell me about its status - whether it is open or not. In other words, if I open the same file it should tell me that the file is already open.
答
尝试这样: / p>
Try this:
Option Explicit
Sub Sample()
Dim Ret
Ret = IsWorkBookOpen("C:\myWork.xlsx")
If Ret = True Then
MsgBox "File is open"
Else
MsgBox "File is Closed"
End If
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function