我已经在excel vba中编写了一个代码,它最初检查定义的word文档是否已经打开。
If IsFileOpen(pathh) Then
MsgBox " Already in use"
Else
MsgBox "Not in use"
End If
Function IsFileOpen(pathh 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.
On Error Resume Next
Open pathh 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
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
但问题是,如果我在运行此代码之前已经打开word文档但是它没有被输入到选择案例代码段中,那么我得到错误70(权限被拒绝)。
而是抛出一个并停止进一步执行代码。
Open pathh For Input Lock Read As #filenum
我想捕获错误编号并将其输入到选择案例中,在该情况下,无论文件是否打开,它都会显示相应的消息