30.04.2017 Views

4523756273

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11: Automatic Procedures and Events<br />

177<br />

Preventing data validation from being destroyed<br />

The procedure in this section demonstrates how to prevent users from copying<br />

data and wiping out data validation rules. This example assumes that the<br />

worksheet has a range named InputArea, and this input area contains data<br />

validation rules (set up by using the Data➪Data Tools➪Data Validation command).<br />

The range can have any validation rules you want.<br />

A workbook that contains this code is available at this book’s Web site:<br />

Private Sub Worksheet_Change(ByVal Target As Range)<br />

Dim VT As Long<br />

‘Do all cells in the validation range<br />

‘still have validation?<br />

On Error Resume Next<br />

VT = Range(“InputRange”).Validation.Type<br />

If Err.Number 0 Then<br />

Application.Undo<br />

MsgBox “Your last operation was canceled.” & _<br />

“It would have deleted data validation rules.”, _<br />

vbCritical<br />

End If<br />

End Sub<br />

The procedure is executed whenever a cell is changed. It checks the validation<br />

type of the range (named InputRange) that is supposed to contain the<br />

data validation rules. If the VT variable contains an error, that means that<br />

one or more cells in the InputRange no longer have data validation (the user<br />

probably copied some data over it). If that’s the case, the code executes the<br />

Undo method of the Application object and reverses the user’s action. Then<br />

it displays a message box.<br />

The net effect? It’s impossible to wipe out the validation rules by copying<br />

data. When Excel is broken, use VBA to fix it.<br />

Events Not Associated with Objects<br />

The events that I discuss previously in this chapter are associated with either<br />

a workbook object or a worksheet object. In this section, I discuss two types<br />

of events that are not associated with objects: time and keypresses.<br />

Because time and keypresses aren’t associated with a particular object such<br />

as a workbook or a worksheet, you program these events in a normal VBA<br />

module (unlike the other events discussed in this chapter).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!