RuinAerlin
New Member
- Joined
- Apr 8, 2016
- Messages
- 10
Good morning,
I use a userform to add lines to a workbook. The file is a shared document and the likelihood is I already have it open but due to the number of open files it's often not easy to see if I do.
I am trying to use the below code for if I already have the file open. However I am not sure this works for when it's me that has it open. I get the error: filename.xlsx is already open. Reopening will cause any changes you made to be discarded. Do you want to reopen filename.xlsx?
My aim is to get it to save and close the file if I am already in it.
I use a userform to add lines to a workbook. The file is a shared document and the likelihood is I already have it open but due to the number of open files it's often not easy to see if I do.
I am trying to use the below code for if I already have the file open. However I am not sure this works for when it's me that has it open. I get the error: filename.xlsx is already open. Reopening will cause any changes you made to be discarded. Do you want to reopen filename.xlsx?
My aim is to get it to save and close the file if I am already in it.
Rich (BB code):
Sub TestFileOpened()
' Test to see if the file is open.
If IsFileOpen("filepath") Then
' Display a message stating the file in use.
Windows("filepath").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
Windows("other filepath").Activate '
Else
' do nothing
End If
End Sub
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