Ken
I have separately posted this query in case you're not online to reply!
I have a database that imports an excel worksheet as part of a vba function.
I have used your posting to get code that checks if the file is open before
I start the import but my query is slightly different, hence the new post
that I also put up.
The excel file I'm importing is on a network and my query is whether I can
retrieve the name of the person who has the file open as the company is quite
big and I'd like to be able to got to the person's PC if they've left the
file open on their PC and/or are not responding to a blanket email to a group
of people to shut the excel file. I'd prefer to go to the person's PC and
shut the file or get them to shut the file rather than close the file on them
and potentially cause their work to be lost.
If I try to open the excel file ordinarily (through Excel and not as part of
a VBA function) and the file is open, I get a message saying that the file is
use and it says the name of the person who has the file open. It gives an
option to open a copy of the file as read-only. Would it be possible to
retrieve the information (i.e name) on the user that has the file open from
this dialog pane/error message as part of the code you have written in your
post?
I presume this error message/dialog pane is the same error that you are
checking for in the code (error num 70) and maybe the code could be altered
to provide the name of the person that has the file open. Is this possible?
--
Andrew
Ken Snell said:
Here is a function that you can call to identify if a file is open:
' This function checks to see if a file is open or not. If the file is
' already open, it returns True. If the file is not open, it returns
' False. Otherwise, a run-time error will occur because there is
' some other problem accessing the file.
Function IsFileOpen(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
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
Here is how you can test if Excel is already open:
Dim objExcel As Object
On Error Resume Next
Set objExcel = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
' Excel is not open
Err.Clear
Set objExcel = CreateObject("Excel.Application")
Else
' Excel is open and you now have an object
' reference to it in objExcel
End If