How to: if a range is not empty don't allow close?

D

dan dungan

Hi microsoft.public.excel.programming group,

I have a command button the copies cells to a text file.

Sometimes the data has not been saved to the text file.

I suspect the users have been closing the workbook before pressing the
command button.

So I tried to this:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

_____________________________________
With Worksheets("CompleteQuote")
Dim rng As Range
Set rng = Range("test_range")
If rng.Value > 0 Then
Cancel = True
MsgBox ("You still have data that has not been exported. Please
cancel.")
Else: Cancel = False
End If
End With
End Sub
_____________________________________


This returns runtime error 13. Type Mismatch on
the following line:
If rng.Value > 0 Then

The range will contain some cells with data and some cells will have
no data.

Please offer any suggestions or questions.

Thanks,

Dan
 
J

JLGWhiz

Not sure what type data you have in the range, but if it is all numeric, then
this should do the trick:
Private Sub Workbook_BeforeClose(Cancel As Boolean)

_____________________________________
With Worksheets("CompleteQuote")
Dim rng As Range
Set rng = Range("test_range")
If Application.WorksheetFunction.Sum(rng) > 0 Then
Cancel = True
MsgBox ("You still have data that has not been exported. Please
cancel.")
Else: Cancel = False
End If
End With
End Sub
 
B

Barb Reinhardt

Try this

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim rng As Range
With Worksheets("CompleteQuote")
Set rng = Nothing
On Error Resume Next
Set rng = .Range("test_range")
On Error GoTo 0
If Not rng Is Nothing Then
Cancel = True
MsgBox ("You still have data that has not been exported. Please
cancel.")
Else
Cancel = False
End If
End With
End Sub
 
D

dan dungan

Hi Barbara,

I agree. The procedure as previously written returned the message box
message every time I tried to close the workbook.

Thanks again to both you and JLGWhiz.

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top