Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Check Workbook Object is not empty

Tags:

excel

vba

I have a workbook object previously created in code, all good.

However, for proper error handling, if the Workbook for whatever reasons gets closed, even though unlikely, I want to check this before further code execution.

The watch window shows the workbook after closure via direct entry (for simulation) with <no variables>:

watches window

However, nothing seems to work to check the workbook object is empty:

Debug.Print IsObject(dWorkbook) ' returns true > expected as obj as such still exists
Debug.Print IsNull(dWorkbook)   ' returns false
Debug.Print IsEmpty(dWorkbook)  ' returns false
Debug.Print TypeName(dWorkbook) ' returns object > expected

If dWorkbook Is Nothing Then    ' steps into Else
    Debug.Print "is Nothing"
Else
    Debug.Print "something"
End If

Thanks for a suggestion here to find a way to the check the workbook object has content.

like image 982
Alex Avatar asked Oct 12 '25 23:10

Alex


1 Answers

Here is one way.

Option Explicit

Sub Sample()
    Dim wb As Workbook
    Dim wsCount As Long
    
    Set wb = Workbooks.Add
    
    '~~> Put a breakpoint here and then close the workbook manually
    On Error Resume Next
    '~~> Check if there are worksheets
    wsCount = wb.Sheets.Count
    On Error GoTo 0
    
    If wsCount = 0 Then MsgBox "WB is Lost" Else MsgBox "WB is Not Lost"
End Sub

If closing the other workbook manually is stopping the code, then use this method. Just add one Userform to your workbook so that you will be able to close the other workbook manually.

Please note that adding the userform is only so that you can test the code manually. In a real scenario, you do not have to add a userform.

Option Explicit

Sub Sample()
    Dim wb As Workbook
    Dim wsCount As Long
    
    Set wb = Workbooks.Add
    
    ThisWorkbook.Activate
    UserForm1.Show vbModeless
    
    '~~> Put a breakpoint here and then close the workbook manually
    On Error Resume Next
    '~~> Check if there are worksheets
    wsCount = wb.Sheets.Count
    On Error GoTo 0
    
    If wsCount = 0 Then MsgBox "WB is Lost" Else MsgBox "WB is Not Lost"
End Sub
like image 100
Siddharth Rout Avatar answered Oct 14 '25 14:10

Siddharth Rout