A way to validate data even if someone uses copy+paste is to simulate
the effect. This needs no VBA. The simulation doesn't stop bad data
from being entered. However, it makes the Excel workbook model
unusable and so protects data integrity.
An added benefit of this approach is that one can use validation
formulae that are disallowed in the data validation dialog box.
The idea is to put the validation in a cell that is protected. If the
entered data are unacceptable, the validation cell displays an error
and the value used in calculations becomes an error code. To make sure
of that, the rest of the model does *not* reference the cells in which
the user enters data but the cells that contain the correct value (or
an error code).
It's actually a lot easier than it appears. Go through the example
below and you'll see the simplicity of this approach.
Suppose in F4 we want the year between 2006 and 2010 and in F5 we want
the month as Jan, Feb, etc., preferably selected from a drop-down list.
Create the list of valid months in some range, say, N1:N12. Name this
range Months.
(Optionally) set data validation for F4 to be a list from the numbers
2006, 2007,..., 2010.
Set data validation for F5 to use a drop down list and enter =Months as
the list.
The above will work fine as long as someone doesn't paste new contents
into F4:F5. Here's how we validate data even after a paste operation!
The real validation will be in cells G4:H5.
In G4 enter =IF(OR(F4<2006,F4>2010,INT(F4)<>F4),"Please enter a
year"&CHAR(10)&"between 2006 and 2010",""). In H4 enter =IF(G4
="",F4,NA())
In G5 enter =IF(F5="","",IF(ISERROR(MATCH(F5,Months,0)),"Bad
month;"&CHAR(10)&"select from the drop down list"&CHAR(10)&"Please UNDO
any paste operations","")). In H5 enter =IF(F5="","",IF(G5="",F5,NA
())). Note that this is different from H4 because of what I believe to
be a bug in how data validation deals with named lists.
The rest of the worksheet/book uses H4 and H5 as the data cells. The
only references to F4:F5 are in the G4:H5 range.
Unlock F4:F5 and protect the worksheet. Now, irrespective of what the
user does to F4:F5, H4:H5 will contain either legitimate values or a
#N/A error code.
A slightly more advanced use of the above approach:
Suppose F6 is supposed to contain the day-of-the-month and we want to
correctly account for leap years between 2006 and 2010. Then, the G6
validation formula would be the array formula =IF(F6="","",IF(OR(F6
<1,F6>IF(OR(H5={"Jan","Mar","May","Jul","Aug","Oct","Dec"}),31,IF(OR(H5
={"Apr","Jun","Sep","Nov"}),30,IF(MOD(H4,4)=0,29,28)))),"Bad
date","")). And, of course, H6 contains =IF(G6="",F6,NA()).
--
Regards,
Tushar Mehta
www.tushar-mehta.com
Excel, PowerPoint, and VBA add-ins, tutorials
Custom MS Office productivity solutions