I have the following code which is supposed to check if a file is open or not. If the file is open then it should do nothing but if the file isn't open then it should display a message saying that the file isn't open and exit the sub.
However, it always exits the regardless if the file is open or not.
Sub Update_Folder()
Dim str As String
Dim openPos As Integer
Dim closePos As Integer
Dim midBit As String
'Creates file string name
str = Range("H6").Value
openPos = InStr(str, "[")
closePos = InStr(str, "]")
midBit = Mid(str, openPos + 1, closePos - openPos - 1)
If Range("B2").Value = "Yes" Or Range("B4").Value = "Yes" Or Range("B5").Value = "Yes" Or Range("B6").Value = "Yes" Or Range("B9").Value = "Yes" Or Range("B12").Value = "Yes" Or Range("B13").Value = "Yes" Then
On Error Resume Next
Set WB = Workbooks(midBit)
If Err Then MsgBox ("Please open the following file(s): " & str)
'Exit Sub
On Error GoTo 0
End If
Call Folder_Creation
END SUB
What is the correct syntax to check if a file is open and if so do nothing but if the file is not open display a msgbox
and exit sub? Cell H6
is C:\Users\User1\Documents\[TestFile.xlsx]
.
I tried the solution from the following link but Detect whether Excel workbook is already open
It does not work for me. Maybe cause I am setting the path based on a file path in a cell? I get a file not found error when running it. The debug
screen takes me to the Case Else: Error ErrNo
line.
UPDATE:
The following code works for me. I had to change Error GoTo
syntax and then move error handler
to the end of the script. So if the error occurs it skips to the bottom of the script
Sub Update_Folder()
Dim str As String
Dim openPos As Integer
Dim closePos As Integer
Dim midBit As String
'Creates file string name
str = Range("H6").Value
openPos = InStr(str, "[")
closePos = InStr(str, "]")
midBit = Mid(str, openPos + 1, closePos - openPos - 1)
If Range("B2").Value = "Yes" Or Range("B4").Value = "Yes" Or Range("B5").Value = "Yes" Or Range("B6").Value = "Yes" Or Range("B9").Value = "Yes" Or Range("B12").Value = "Yes" Or Range("B13").Value = "Yes" Then
On Error goto ErrorHandler1:
Set WB = Workbooks(midBit)
If Err Then MsgBox ("Please open the following file(s): " & str)
'Exit Sub
Call Folder_Creation
ErrorHandler1:
MsgBox ("Please open the following file(s): " & str)
Exit Sub
END SUB