Is book valid


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'**********************************************************************************************************
' Name:                 isBookValid
' Author:               mielk | 2013-04-25
'
' Comment:              Function to check if the given Excel workbook is valid and you can refer to its
'                       properties and methods without errors.
'
'                       Using this function is very helpful since it lets you avoid
'                       Run-time error '-2147221080 (800401a8)': Automation error.
'                       This error is generated, when the code tries to refer to a property or a method
'                       of an Excel workbook that had been already closed.
'
' Parameters:
'   wkb                 The Excel workbook to be checked.
'
' Returns:
'   Boolean             True - if the given workbook is valid and you can refer to it without any errors.
'                       False - if the given workbook is invalid, that means it is corrupted or had been
'                               closed or deleted before this method has been called and referring to it
'                               will raise an error.
'
'
' --- Changes log -----------------------------------------------------------------------------------------
' 2013-04-25        mielk       Function created.
'**********************************************************************************************************
Public Function isBookValid(wkb As Excel.Workbook) As Boolean
    Const METHOD_NAME As String = "isBookValid"
    '------------------------------------------------------------------------------------------------------
    Dim strBookName As String
    '------------------------------------------------------------------------------------------------------

    On Error Resume Next
    strBookName = wkb.name

    'Check method is very easy - if the name of the given workbook has been assigned to the variable
    '[strBookName], this workbook is valid and you can refer to it. Otherwise, error would be generated
    'and step [strBookName = wkb.name] would be skipped because of [On Error Resume Next] statement above.
    isBookValid = VBA.Len(strBookName)

End Function