This seems to be an easy function and solution should be straight forward, but I can't find the problem.
I have a function that gets called in a sub, it checks if the file is open, if not, to open it.
The function runs perfectly but when it returns to the main sub that's calling it, the variable (True or False) loses its value and I get an error 9: subscript out of range on the line Set wb = Workbooks(MasterFileF) in the main sub.
Function wbOpen(wbName As String) As Boolean
Dim wbO As Workbook
On Error Resume Next
Set wbO = Workbooks(wbName)
wbOpen = Not wbO Is Nothing
Set wbO = Nothing
End Function
Sub Macro5()
Dim wb As Workbook
Dim path As String
Dim MasterFile As String
Dim MasterFileF As String
Application.ScreenUpdating = False
'Get folder path
path = GetFolder()
If path = "" Then
MsgBox "No folder selected. Please start macro again and select a folder"
Exit Sub
Else
End If
MasterFile = Dir(path & "\*Master data*.xls*")
MasterFileF = path & "\" & MasterFile
'Check if workbook open if not open it
If wbOpen(MasterFile) = True Then
Set wb = Workbooks(MasterFileF)
Else
Set wb = Workbooks.Open(MasterFileF)
End If
Where am I going wrong that the Function variables' values get lost when it returns to the main sub?
F8?On Error Resume Nextbut do reset it. UseOn Error Goto 0to do that. Also, I wouldn't use that approach, I would loop through theWorkbooksin theApplication.Workbookscollection to find the workbook.wbOpenwhich is supposed to be True or False goes empty