Я бы немного перевернул твой код
, чтобы пометка Wb Open() f
возвращала открытую книгу, если она найдена, через ее аргументы
Function wbOpen(wbName As String, wbO As Workbook) As Boolean
On Error Resume Next
Set wbO = Workbooks(wbName)
wbOpen = Not wbO Is Nothing
End Function
и затем в твоем главном просто код go:
MasterFile = Dir(path & "\*Master data*.xls*")
If Not wbOpen(MasterFile, wb) Then Set wb = Workbooks.Open(path & "\" & MasterFile)
Редактировать
, чтобы добавить расширенную версию для обработки книги с одинаковыми именами, но разными путями
, в этом случае вы должны проверить оба имя файла и путь, но на разных шагах
, поэтому WbOpen()
функция становится:
Function wbOpen(wbName As String, wbPath As String, wbO As Workbook) As Boolean
On Error Resume Next
Set wbO = Workbooks(wbName)
On Error GoTo 0 ' restore error handling back
If Not wbO Is Nothing Then ' in current excel session there already is an open workbook with same name (path excluded) as the searched one
If wbO.path = wbPath Then ' the already open workbook has the same path as the searched one -> we got it!
wbOpen = True
Else ' the already open workbook has a different path from the searched one -> we must investigate ...
If MsgBox("A workbook named after:" _
& vbCrLf & vbCrLf & vbTab & wbName _
& vbCrLf & vbCrLf & " is already open but its path is different from:" _
& vbCrLf & vbCrLf & vbTab & wbPath _
& vbCrLf & vbCrLf & "If you want to open the new found one, the already open one will be closed" _
& vbCrLf & vbCrLf & vbCrLf & "Do you want to open the new found one?", vbQuestion + vbYesNo) = vbYes Then
wbO.Close True ' close the currently opened workbook with same name but different path from searched one
' the opening of the new one will be made in the main sub, after this function returning 'False'
Else
wbOpen = True ' you chose not to open the searched one and stay with the currently open one -> return 'True' to say you are done
End If
End If
End If
End Function
и соответствующая часть вашего основного кода изменится на:
MasterFile = Dir(path & "\*.xls*")
If Not wbOpen(MasterFile, path, wb) Then Set wb = Workbooks.Open(path & "\" & MasterFile)