Workbook close event not working right

TheWennerWoman

Active Member
Joined
Aug 1, 2019
Messages
303
Office Version
  1. 365
Platform
  1. Windows
Hello,

I have this
VBA Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)

With Worksheets("Uploader")
        If .Visible And posted = 0 Then MsgBox ("You haven't uploaded data to the database!"), vbCritical
        Cancel = True
End With
End Sub

"posted" is a public variable that gets flipped to 1 when the data is uploaded to the database correctly.

If I make the worksheet "uploader" very hidden and attempt to close, the code above kicks in when I don't think it should?

I'm guessing my syntax is wrong somewhere?

Thanks as always for any advice!
 

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
It's a common mistake: Worksheet.Visible is not a Boolean (it has 3 possible values). Since xlSheetVeryHidden has a value of 2, if you coerce that to a Boolean it will return True as it is non-zero. You should explicitly test if it is visible like this:

VBA Code:
If .Visible = xlSheetVisible
 
Upvote 1
Hi
try this update to your code & see if resolves your issue

VBA Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)

    With Worksheets("Uploader")
            If .Visible = xlSheetVisible And Posted = 0 Then
                MsgBox "You haven't uploaded data to the database!", vbCritical, "Attention"
                Cancel = True
            End If
    End With
    
End Sub

Dave
 
Upvote 1
Solution
Thanks both, each solution works perfectly - can only mark one as the answer though.
 
Upvote 0
I'm going to mark Dave's solution as the answer as it also addresses the other issue that your Cancel = True would always be executed with your original version as it wasn't part of the If block.
 
Upvote 1

Forum statistics

Threads
1,224,823
Messages
6,181,177
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top