Note: This is an advanced topic on data validation. For an introduction to data validation, and how to validate a cell or a range, see Add data validation to a cell or a range.
You can use data validation to restrict the type of data or values that users enter into cells. For example, you might use data validation to calculate the maximum allowed value in a cell based on a value elsewhere in the workbook. In the following example, the user has typed abc , which is not an acceptable value in that cell.
When is data validation useful?
Data validation is invaluable when you want to share a workbook with others, and you want the data entered to be accurate and consistent. Among other things, you can use data validation for the following:
-
Restrict entries to predefined items in a list— For example, you can limit a user’s department selections to Accounting, Payroll, HR, to name a few.
-
Restrict numbers outside a specified range— For example, you can specify a maximum percentage input for an employee’s annual merit increase, let’s say 3%, or only allow a whole number between 1 and 100.
-
Restrict dates outside a certain time frame— For example, in an employee time off request, you can prevent someone from selecting a date before today’s date.
-
Restrict times outside a certain time frame— For example, you can specify meeting scheduling between 8:00 AM and 5:00 PM.
-
Limit the number of text characters— For example, you can limit the allowed text in a cell to 10 or fewer characters.
-
Validate data based on formulas or values in other cells— For example, you can use data validation to set a maximum limit for commissions and bonuses based on the overall projected payroll value. If users enter more than the limit amount, they see an error message.
Data Validation Input and Error Messages
You can choose to show an Input Message when the user selects the cell. Input messages are generally used to offer users guidance about the type of data that you want entered in the cell. This type of message appears near the cell. You can move this message if you want to, and it remains visible until you move to another cell or press Esc.
You set up your Input Message in the second data validation tab.
Once your users get used to your Input Message, you can uncheck the Show input message when cell is selected option.
You can also show an Error Alert that appears only after users enter invalid data.
You can choose from three types of error alerts:
Icon |
Type |
Use to |
Stop |
Prevent users from entering invalid data in a cell. A Stop alert message has two options: Retry or Cancel. |
|
Warning |
Warn users that the data they entered is invalid, without preventing them from entering it. When a Warning alert message appears, users can click Yes to accept the invalid entry, No to edit the invalid entry, or Cancel to remove the invalid entry. |
|
Information |
Inform users that the data they entered is invalid, without preventing them from entering it. This type of error alert is the most flexible. When an Information alert message appears, users can click OK to accept the invalid value or Cancel to reject it. |
Tips for working with data validation
Use these tips and tricks for working with data validation in Excel.
Note: If you want to use data validation with workbooks in Excel Services or the Excel Web App you will need to create the data validation in the Excel desktop version first.
-
The width of the drop-down list is determined by the width of the cell that has the data validation. You might need to adjust the width of that cell to prevent truncating the width of valid entries that are wider than the width of the drop-down list.
-
If you plan to protect the worksheet or workbook, protect it after you have finished specifying any validation settings. Make sure that you unlock any validated cells before you protect the worksheet. Otherwise, users will not be able to type any data in the cells. See Protect a worksheet.
-
If you plan to share the workbook, share it only after you have finished specifying data validation and protection settings. After you share a workbook, you won’t be able to change the validation settings unless you stop sharing.
-
You can apply data validation to cells that already have data entered in them. However, Excel does not automatically notify you that the existing cells contain invalid data. In this scenario, you can highlight invalid data by instructing Excel to circle it on the worksheet. Once you have identified the invalid data, you can hide the circles again. If you correct an invalid entry, the circle disappears automatically.
To apply the circles, select the cells you want to evaluate and go to Data > Data Tools > Data Validation > Circle Invalid Data.
-
To quickly remove data validation for a cell, select it, and then go to Data > Data Tools > Data Validation > Settings > Clear All.
-
To find the cells on the worksheet that have data validation, on the Home tab, in the Editing group, click Find & Select, and then click Data Validation. After you have found the cells that have data validation, you can change, copy, or remove validation settings.
-
When creating a drop-down list, you can use the Define Name command (Formulas tab, Defined Names group) to define a name for the range that contains the list. After you create the list on another worksheet, you can hide the worksheet that contains the list and then protect the workbook so that users won’t have access to the list.
-
If you change the validation settings for a cell, you can automatically apply your changes to all other cells that have the same settings. To do so, on the Settings tab, select the Apply these changes to all other cells with the same settings check box.
-
If data validation isn’t working, make sure that:
-
Users are not copying or filling data — Data validation is designed to show messages and prevent invalid entries only when users type data directly in a cell. When data is copied or filled, the messages do not appear. To prevent users from copying and filling data by dragging and dropping cells, go to File > Options > Advanced > Editing options > clear the Enable fill handle and cell drag-and-drop check box, and then protect the worksheet.
-
Manual recalculation is turned off — If manual recalculation is turned on, uncalculated cells can prevent data from being validated correctly. To turn off manual recalculation, go to the Formulas tab > Calculation group > Calculation Options > click Automatic.
-
Formulas are error free — Make sure that formulas in validated cells do not cause errors, such as #REF! or #DIV/0!. Excel ignores the data validation until you correct the error.
-
Cells referenced in formulas are correct — If a referenced cell changes so that a formula in a validated cell calculates an invalid result, the validation message for the cell won’t appear.
-
An Excel table might be linked to a SharePoint site — You cannot add data validation to an Excel table that is linked to a SharePoint site. To add data validation, you must unlink the Excel table or convert the Excel table to a range.
-
You might currently be entering data — The Data Validation command is not available while you are entering data in a cell. To finish entering data, press Enter or ESC to quit.
-
The worksheet might be protected or shared — You cannot change data validation settings if your workbook is shared or protected. You’ll need to unshare or unprotect your workbook first.
-
How to update or remove data validation in an inherited workbook
If you inherit a workbook with data validation, you can modify or remove it unless the worksheet is protected. If it’s protected with a password that you do not know you should try to contact the previous owner to help you unprotect the worksheet, as Excel has no way to recover unknown or lost passwords. You can also copy the data to another worksheet, and then remove the data validation.
If you see a data validation alert when you try to enter or change data in a cell, and you’re not clear about what you can enter, contact the owner of the workbook.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Having multiple users of a workbook is a perfect brew for a barrel of problems. Imagine anyone having access to editing anything. Your reports will quickly become subject to alteration, human errors, and someone’s quirks.
A complete shield against that would be protecting the sheet/workbook. This will lock the sheet/file from any alteration or you can choose the option of selective alteration where all the cells on the sheet are protected except chosen ones. Now if only you can control what type of data goes into the selectively open cells too?
Find that wish granted because in today’s Data Validation lineup, we’re going into the details of what Data Validation is, how to apply it, the limitations, the options and settings, some examples of Data Validation rules, and all the tidbits of finding, removing and copying Data Validation.
You have got to be wondering what the essence of Data Validation is so…
Let’s get validating!
What is Data Validation?
Data Validation in Excel limits the type of data users can enter into a cell. E.g., if you are entering game scores with a score range of 1 to 5, you can use Data Validation to control the scores that go in the target cells to be between 1 to 5.
While that is the prime role of Data Validation, its prime use is creating a drop-down menu for a cell.
The options in Excel provide a list of rules to choose from. These rules determine the type of data that can be entered on selected cells on the worksheet. It is here that you will find the option of adding a drop-down list.
Using these rules, you can control the data type in the cell to be only numbers, dates, time, and characters of a given length, selected from a drop-down list (list also created using Data Validation), or you can define the criteria through a custom formula. An Input Message can be displayed with a cell with or without a validation rule added.
When Data Validation is applied to a selection of cells and invalid data is entered by the user, an error alert will be displayed:
This is the default alert and through Data Validation, you can create a custom alert. Another feature of Data Validation is adding an Input Message to a cell that is quite identical to a comment in Excel.
That is what Excel’s Data Validation is in a nutshell. We’re sure you’re ready to jump to the how-to and we have it coming for you. We’ll begin with a simple case of adding Data Validation.
How to Add Data Validation?
Where will you find the Data Validation button? Hint: The Data tab. Everything you need from Data Validation can be found in the Data Validation icon in the Data Tools group. Now let’s see how to add Data Validation on the worksheet.
As a small example, let’s assume we are entering a passcode in a cell and you want it to pose an alert when an incorrect key is punched in. Use the steps ahead to add Data Validation to a cell to restrict the type of data that gets entered into the cell:
- Select the cell(s) you want to add Data Validation
- Go to the Data tab and click on the Data Validation icon in the Data Tools
- You will see a small Data Validation dialog box where all the main Data Validation business will take place. Currently, you can see that the validation criteria allow any value, without any restriction:
- We’re about to change that. In our example case, we want to ensure that all passcodes are 5-digit pins between 10000 to 99999. The Whole number rule will do for this.
- Make the following changes to the Data Validation settings:
- Click on the arrow in the Allow field and choose Whole number.
- In the Data drop-down list, select between.
- In the Minimum and Maximum fields, enter the smallest and largest number of the range you want to allow in the selected cell (i.e. 10000 and 99999 for us).
- When done, select the OK
The Data Validation dialog box will close. You will not see any overt changes since Data Validation is related to entering data. So go ahead and try to enter some invalid data in the cell e.g. we can try entering a 4-digit number. We will get an error alert.
The Retry button gives another attempt at entering the valid data type. The Cancel button wipes out the data we have entered and the Help button redirects us to the Microsoft Support webpage. So yes, you really have no way around this other than entering the relevant type of data.
Overriding Data Validation
Right now, Data Validation might be looking all types of invincible but it has a couple of chinks in its armor. The first is that if Data Validation is applied to occupied cells, the values will stay as they are; there will be no rectification and no notification or indication that the data is invalid.
Secondly, if invalid data is value-pasted to a cell containing a Data Validation rule, while the rule will still stand, the invalid data won’t be restricted from being pasted and there will again be no rectification or indication of invalid data.
This shows us that Data Validation is only a data-entry control and will only work for data that is being entered; not data that already exists or is being pasted.
Now that you’re getting a basic idea of what Data Validation does, we’ll explore the Data Validation dialog box before we go into the scope of Data Validation with some examples.
Excel Data Validation Options & Settings
You just saw how to access the Data Validation settings from the Data tab. Let’s go through the rules and options in the settings to understand what types of data entry Data Validation can control.
Settings
Firstly, the face of the Data Validation options; the Settings tab. To set validation criteria or rules, you begin with choosing a rule from the Allow menu. If you do not find a suitable preset criterion, you can use the Custom option. Here you will need a formula to define the Data Validation criteria. We’ll briefly go over the preset rules.
Any value
This is the default setting when no Data Validation is applied. Any value can be entered in the cells without any restriction. You can still add an Input Message to the cell(s) but for an error alert to show, there needs to be a rule in place.
Whole number
Allow only whole numbers to be entered in cells. You can further set the limit value(s) that will go into these cells once Data Validation is applied.
Additional fields become accessible with the rules. E.g. when you select the Whole number criteria, from the Data field you can choose if the number should fall between a provided range or should be equal to or greater/less than a certain value.
Decimal
This is the decimal variant of the Whole number rule since the latter doesn’t allow decimal. The options are the same with Decimal as they are with Whole number; only that the data entered will allow decimal and whole numbers that meet the specified range of values.
List
Create a drop-down list for a cell with this rule. The content of the list can be entered into the provided field in the Data Validation dialog box or can be referred to from the worksheet.
Unchecking the In-cell dropdown box will remove the drop-down menu which kind of kills the whole mojo of this rule but what will happen is that only the specified values can then be entered in the cell. The values manually entered using this rule will be case-sensitive.
Date
Restrict the data in the cells to be only entered as dates with the Date criterion. Set a start and/or end date to further limit the dates that will go on the worksheet.
Time
The Time rule will only allow time values in the cells. Entries can additionally be controlled by specifying the start and/or end time.
Text length
Text length limits the number of characters (whether numbers, letters, or symbols) that go into the cells.
Custom
Add a custom formula to expand the scope of Data Validation when you can’t find a match for your requirement in the predefined rules.
Checkbox – Ignore blank
Throughout the Data Validation rules, you may have noticed an Ignore blank checkbox. The role of this box is to ignore the blank cells from being treated as cells with invalid data since blank cells will not match most Data Validation criteria. Leave this box checked if you don’t want blank cells to be circled when circling invalid data (found out more about this feature later).
Checkbox – Apply these changes to all the other cells with the same settings
Let’s say you’ve selected a cell with Data Validation and open the Data Validation dialog box. When you mark this checkbox, all other cells on the worksheet that have the same validation criteria applied to them will be selected in the background.
This is useful if you don’t remember all the cells that you have applied a Data Validation rule to and want to select all the cells with that rule.
Button – Clear All
Clears Data Validation (comprising the validation rule and Input Message) from the selected cell, restoring the validation criterion to Any value.
Input Message
Onto the next tab in the Data Validation dialog box. This is the Input Message tab where you will learn about the settings regarding displaying an Input Message with a cell. The message will be displayed when the cell is selected and looks like an Excel cell comment.
This is an optional feature and merely a display item. Use an Input Message to notify a user about the contents of the cell, or the data type to be entered.
Let’s pick the example we were working on previously and see how we can add an Input Message to a cell.
- Select the cell(s) that you want displayed with the Input Message.
- Open the Data Validation dialog box from the Data tab > Data Tools group > Data Validation Then go to the Input Message tab.
- Enter the title (optional) to display as the Input Message header as we have added “Passcode”.
- Then add the Input Message in the given field.
- Click on the OK command to apply the settings.
Now, whenever that cell is selected, you will see the related Input Message in a pale yellow box.
You will not see the Input Message if the relevant cell is not selected. Uncheck the Show input message when cell is selected box to stop the message from appearing.
This will not affect the Data Validation rule and you can enable the message any time again. However, you can also clear the title and message from the Input Message tab if there will be no use for it later.
The Clear All button will reset the settings of the entire Data Validation dialog box, Settings tab included.
Error Alert
This tab deals with the error alert that will be displayed when invalid data is entered in the cells with Data Validation. Excel has three styles of error alerts to choose from with each style having different commands and control. Let’s run you through each of them so you know which error alert you would want to deploy.
The standard title of the alert is “Microsoft Excel” and the error message is «This value doesn’t match the data validation restrictions defined for this cell.» if nothing is specified otherwise.
Stop
The Stop alert is the default error alert displayed when you set a Data Validation rule. It appears with a cross icon. The title and error message can be added by the user which will overwrite the standard alert. The settings are the same for all error alerts.
The Stop alert restricts entering invalid data; with the Retry button, you will have to try entering the data again, the Cancel button will clear the entered data and the Help button will guide you to the support center.
Hence, with this alert style, there is no getting around «entering» invalid data. Why have we emphasized entering? There are ways around getting invalid data on the worksheet despite setting Data Validation and we’ll come to that later.
Use the Style list in the dialog box to switch to another alert style.
Warning
The Warning error alert, shown with an exclamation point icon is a softer alert that gives the user the option of retrying the entry (by using the No button) but also gives the space of continuing with the invalid entry (by using the Yes button).
Edit the title and message in the Data Validation dialog box if preferred.
Information
An even softer error alert form, the Information alert only lays out information (the default error message unless changed by the user) regarding the input data. Invalid data will still be accepted after clicking on the OK button. This alert is actually just like a reminder with hardly any restricting quality.
Other than the alert styles, in the Data Validation dialog box, there’s a Show error alert after invalid data is entered checkbox and if you unmark it, even with the Data Validation rule set, no validation will be performed.
The use of this checkbox makes sense to temporarily disable the validation so the rule and error style is still saved to be enabled later. Unmarking the checkbox is also of use when you want to give the user the option to choose from a Data Validation list and also of adding a new value.
Data Validation Examples
What we have covered majorly until now is how to add Data Validation, what the options and settings entail, and different types of error alerts. Now we’ll proceed to different examples where we can apply different Data Validation rules so you know how to use Data Validation for your worksheets.
Heading back to the Settings tab in the Data Validation dialog box, here goes the first rule.
Whole number
The first couple of steps of applying Data Validation is to select the target cells and to open the Data Validation dialog box to set the criteria. To open the dialog box, go to the Data tab > Data Tools group > Data Validation icon.
We’re working on the Whole number Data Validation criterion. In the case example below, we are filling out students’ marks in an exam. We have the Data criterion set to between to define what numbers the marks should be between.
The limits that we have set for the lowest marks is 0 and the highest has been set to 50 marks by entering F3 as an absolute reference so it remains fixed for the rest of the selection. Instead of entering 50 directly as the upper limit, we have referred a cell so that we can enter different total marks for tests and exams that Data Validation will automatically take into account.
Now click OK and try entering a number beyond the range of the specified limits. See what happens.
You will get an error alert and you will know that you have entered invalid data. Try re-entering the value in compliance with the Data Validation criteria.
The Decimal rule works in the same way; only that it allows decimal whereas the Whole number rule doesn’t. If you’re dealing with decimals and integers, you can apply the Decimal rule as it also allows integers in the specified range to be entered.
List
Creating a small and simple list would require nothing more than punching in the items of the intended list, delimited by commas, as the source:
But see this?
This comes readymade for no one but it can be achieved in some surprisingly simple steps. This is a drop-down menu created for every cell. For data entry, this is a dream and is made using the List rule in Data Validation.
But before we get to the List rule, we need to lay out a couple of things in advance. Create a list of the items you want in the drop-down menu, name that range, then create a Data Validation list with the Named Range.
The list for the Named Range can be on the same worksheet as the target validation data or a different sheet. If you prefer the list hidden, you can keep it on the same sheet in a white font. Now you can check out the steps to create in-cell drop-down menus with Data Validation using a Named Range from a separate sheet.
- Form a list of the items you want in the drop-down menu on a separate worksheet.
- Select the items of the list excluding the header.
- Click on the Name box in the corner and type a name for this list.
- After typing the name for the range (our Named Range is Services), hit the Enter
- The Named Range is ready.
- Now go back to the sheet where you’re entering the data. Select the cells that you want to add drop-down lists to.
- From the Data tab, select the Data Validation icon in the Data tools group.
- Choose List from the Allow
- Click on the Source field and press the F3
- A Paste Name box will be launched. Select the relevant Named Range, then press the OK
- The Named Range will appear in the Source field.
- Select the OK command on the Data Validation dialog box too.
The dialog box will close and the in-cell drop-down lists will be added to the selected cells. The arrow to access the drop-down list for a cell will appear when the cell is selected. Now the drop-down lists can be used to start data entry!
If an entry is punched in that doesn’t completely match one of the items of the list, it will be blocked by Data Validation.
Other than looking nifty, using in-cell drop-downs keeps the data entries consistent too.
Dynamic List
With a dynamic list, if you add an item to it, it will automatically be updated in the cell drop-down lists. The way to do that is to create an Excel Table out of the list (with header) along with making a Named Range out of it (without header).
Carrying on with the method we have shown you earlier, we can also extend the Named Range and the cell drop-downs will be updated as per the Named Range.
Let’s assume we are adding just one more service to the list. Add the item in the list that is on the separate sheet. Then select the original Named Range (Services in our case) without the new addition.
Open the Name Manager (Ctrl + F3 keys) and extend the range from B3:B9 to B3:B10. This will include the new item in the range.
Now when you check the in-cell drop-downs on the original sheet, it will include the new item!
The other method is to create a Table before naming the range. Select the list with the header and create a Table from the Home tab > Styles group > Format as Table icon, selecting a table style from the menu.
Once the same data is the items of a Table and Named Range, additions will automatically be incorporated in the cell drop-down lists. This works because an Excel Table is dynamic in nature and automatically includes additions.
The Table will also update the Named Range which will in turn update the in-cell drop-down menus.
Date
Use the Date rule to apply a Data Validation layer to dates in Excel. Not only will this ensure that the input data are dates but also that the dates are within the specified range.
For the example case, we have an extract of some sales data and are filling out the order and delivery dates of the products for the month of September. Begin by selecting the cells, opening the Data Validation dialog box, and selecting the Date criterion from the Allow section.
Now select between from the Data section to add the start and end dates. To keep the dates entered on the worksheet limited to September, the start date will be the 1st of September and the end date will be the 30th of September.
The dates can be fed directly in the dialog box or from the worksheet. To add them in the dialog box, use an Excel date format e.g. 9/1/2022.
Make sure to secure the dates as absolute references if added from the sheet and hit the OK button when done.
Any date added in the cells with Data Validation that is out of the range of the start and end dates will trigger the error alert.
Time
With the Time rule applied, no other input value will be accepted other than a time entry. Using a small example, we’ll show you the format to use in Data Validation for limiting the cells to contain a time value.
Setting up a meeting schedule for office hours would require the office timings as the start and end time. The format to use in the dialog box is 8:00:00 AM.
Tip: On the worksheet, change the format of a free cell to a Time format, enter the time and refer this cell in the Data Validation dialog box or copy the value and paste it in the dialog box.
Apply the rule and you won’t be able to enter values other than time within the mentioned time range set through Data Validation – confirms error alert.
Text length
We’ll now take an example where we are to limit the text length of a cell. You will be able to enter any type of character in text as long as the number of characters abides by the set text length.
As an example, we’ll confine the text length of our data column to equal 10 characters so that the phone numbers fed therein have a lesser chance of being subject to human error.
In the Data Validation dialog box, select the Text length rule. Choose the equal to option in the Data drop-down list and set the phone number digit length e.g., to 10.
Activate these settings by clicking OK. Data Validation will make sure that the entered phone numbers aren’t a single digit above or below 10.
Custom
This rule calls for a custom formula and the aim is to make it go beyond the functions of the preexisting rules in Data Validation and increase its scope. When it comes to custom formulas, there is so much that becomes open to us and that is why that calls for a whole section on its own.
Without further ado, we’ll start with Data Validation with custom formulas.
Formula-based Validation Rules
Earlier, we have been directly adding values or referring values from the worksheet to set the validation criteria which limits the use of Data Validation to the preset rules.
In this section, we are going to talk about using formulas in the preset and custom rules and throwing Excel functions into the works which will greatly expand Data Validation controls.
Dynamically limiting dates to 7 days before the current date, only entering weekdays, entering products of a specific code. This is definitely your regular Data Validation so learn how to do all of this below.
Tip: Using formulas in dialog boxes can be a little tricky because if it fails, it would be hard to pinpoint and tweak what part of the formula isn’t working. Use the formula on the worksheet first to see how it performs and then paste it in the dialog box.
7 Days Before & After TODAY
Let’s take today’s date as the 24th of September 2022. We’re filling out our worksheet containing the order and delivery dates of products that is forwarded daily to the dispatch department. The timeline is 15 days i.e. 7 days before and after the current date inclusive.
That makes our start and end date 17/9 and 1/10 respectively. And we can very well enter these dates directly but that will make a static limitation of the date range.
To keep the Data Validation dynamic, we’ll incorporate the TODAY function. The TODAY function returns the current date in the d/m/yyyy format. In the Data Validation dialog box, select Date and between as the first two criteria and enter the other two as:
Start date:
=TODAY()-7
End date:
=TODAY()+7
The start date is set to be 7 days before the current date and the end date is 7 days after. This keeps our range at 15 days.
For the current date, you will not be able to enter a day after 01-09-2022 and the next day the limit will become 02-09-2022 automatically.
Only Weekdays
Now let’s suppose we’re closed for the weekends; we will need to make sure that the delivery dates are only assigned to weekdays. Data Validation on its own wouldn’t know how to restrict date entries to just the weekdays but it can take the help of a formula and that’s where the WEEKDAY function comes in.
The WEEKDAY function, when fed a date, returns a number from 1 to 7 indicating the day of the week the date falls on.
Access the Data Validation dialog box from the Data tab and choose the Custom criteria. The only other requirement now will be a formula so enter this one in the given field:
=WEEKDAY(D3,2)<6
First off, the second argument of the WEEKDAY function, that is “2” in our example case, is the number for the type of week (Monday to Sunday). To pick a different week type, start punching the function on the worksheet and select the type from there.
In the formula mentioned above, the WEEKDAY function checks what day the date in D3 falls on (Tuesday in this case) and returns the number of Tuesday as per the selected week type. According to week type 2, Tuesday is the second day of the week so the outcome of the WEEKDAY function is 2.
In the other part of the formula, we have <6. With this bit, 6 being the number for Saturday, we are ensuring that the result of the WEEKDAY function is lesser than 6 and hence, earlier than Saturday. Since 2 is lesser than 6, the first date i.e. 20/9/2022 is good to go.
Try entering a weekend date; that’s foolproof Data Validation there:
Applying the same formula on the sheet confirms that the corresponding numbers of all the days are less than 6:
Beginning with Specific Characters
Data Validation can limit the entries beginning with specific characters. To track the entries, we’ll use the COUNTIF function that counts the number of cells in a range that fulfills the defined condition.
The product codes we are using in our case example are made up of product category initials (e.g. HL is for Home & Lifestyle) and then a 4-digit number code.
Use the following formula to only list the products with HL as the starting code:
=COUNTIF(B3,"HL-*")
Don’t worry about setting a different Data Validation rule separately if you’re aiming for two codes instead of one. Just add a plus sign + and repeat the formula with the other code:
=COUNTIF(B3,"HL-*")+COUNTIF(B3,"EA-*")
The COUNTIF function checks B3 for the code HL- in the beginning. The asterisk is added as a wildcard character that will take place of any number of characters in the formula since the product code will obviously have a different mix of numbers.
If the entry meets the condition of beginning with the code HL or EA, it will be accepted by Data Validation while the others will be blocked:
For grouping purposes, you’ll find sorting and filtering easier but for blocking other entries, Data Validation is the go-to. How would things change if, instead of the beginning, the characters were in the middle of the product code? Read on.
String Containing Specific Characters
By now, you have probably realized that we can get Data Validation to do so much more than the basics that it only becomes a matter of using the right formula.
If your characters of interest are anywhere in the string, beginning, mid or end, they can still come under the band of Data Validation using the FIND or SEARCH function.
The FIND function returns the position of the baby text string from the parent text string. You can use either of the two functions; the FIND function is case-sensitive while the SEARCH function is not. Use this formula with the Custom criteria in the Data Validation dialog box:
=FIND("HL",B3)
Just the FIND function on its own will restrict product codes without HL from being entered:
The formula didn’t find HL in the last code and so it cannot be entered:
You can apply this limitation regarding any character or number of characters. E.g. to allow only email IDs as the input, we can use the following formula:
=FIND("@",B3)
Assuming B3 is the first cell of the selection of the range where we are applying Data Validation.
No Duplicates
Here’s one more flex of Data Validation for the day; blocking duplicate entries. Making the COUNTIF function part of a custom formula, we can restrict repeated entries in the cells that Data Validation has been applied to.
Let’s take this example. While noting down entries for an interschool creative writing competition, we realized we could be making the same entry twice and we also realized that it would be a good idea to prevent that from happening in the first place.
Look at this formula and enter it in the formula field using the Custom rule in the Data Validation dialog box:
=COUNTIF($B$3:$B$17,B3)<2
The range that we want to keep free of duplicates is B3:B17. The condition is that the occurrence of B3 in the mentioned range should be less than 2 (you could also write =1). This way, any entry cannot be made twice as each input will be checked against the rest of the range.
An attempt at re-entering the same student failed!
Here’s some food for thought. The Goblet of Fire could have been secretly wired to Excel. Think about it.
Find Invalid Data on the Sheet
When you apply Data Validation to a dataset or paste values on Data Validation cells, you will not be notified of invalid data and it may seem that everything is spot on.
Indication: you will have to find the invalid data on the sheet. Good thing that’s not a very technically far-out problem. By invalid data, we are referring to the value in the cell not meeting the cell’s Data Validation criteria.
There’s an option in the Data Validation menu to circle all the invalid data on the sheet with a red border. We like to call that Excel’s teacher syndrome.
To find all the invalid data as per the Data Validation rule governing those cells, head to the Data tab’s Data Validation icon and click it and select the Circle Invalid Data option.
And that’s it! All the invalid data of all Data Validation rules on the sheet will be circled in red:
And when you want the teacher gone and want to take down all the red circles, use the Clear Validation Circles option or save the file to erase the highlighted invalid data.
If you find that the circling isn’t working properly, use Find & Select to ensure if Data Validation is applied to those cells or not because obviously; the data will be invalid only if Data Validation has been applied in the first place. Speaking of Find & Select, do you know how to use this feature for Data Validation?
How to Find Cells with Data Validation
You may have a good few Data Validation rules spread across your spreadsheet and you’re not about to manually check every other cluster of datasets for validation. Here’s an easy way to find out which cells are using Data Validation and it is with the Find & Select feature. Find & Select will select all the cells with Data Validation no matter how many rules and how dispersed they are.
To find all cells on the worksheet with Data Validation applied, on the Home tab, click on the Find & Select icon in the Editing group. From the menu, select Data Validation.
In our example case, we have applied one Data Validation rule on C3:C12 and another on F3. Both lots have been selected, confirming their Data Validation status.
Note: How does this method differ from the Apply these changes to all the other cells with the same settings checkbox? If you want to find the cells covered by all the Data Validation rules in a sheet, go ahead with Find & Select. To find the cells covered by one particular rule, go ahead with the checkbox.
How to Edit Data Validation Rules
Editing one Data Validation cell is easy from the settings but how do we edit all the cells that carry the same rule? While editing, there’s one small bit you need to take care of and it’s the Apply these changes to all the other cells with the same settings box.
You can edit cells of one rule at a time whether a single cell, a range of cells, or all the cells of a single rule. To edit all the cells belonging to a rule select any cell containing that rule and open the Data Validation dialog box using the Data Validation icon.
Edit the rule according to your requirement; we are changing the text length from 10 to 11 digits. Next, mark the Apply these changes to all the other cells with the same settings checkbox. As soon as you do, all the cells with the original rule will be selected in the background.
Apply the changes and check if you can get away with entering invalid data.
How to Remove Data Validation Rules
Removing Data Validation requires using the Clear All button in the Data Validation dialog box and how much Data Validation you want to remove will depend on the selection of cells.
Remove Data Validation from a single cell by selecting that cell and accessing the Data Validation dialog box. In the Settings tab, click the Clear All button in the bottom-left corner. This will clear the selected cell of the Data Validation rule and Input Message and will reset the Error Alert settings.
The OK command will seal the clearing of settings and you can see below that we are not bound to enter an 11-digit number now:
Remove Data Validation from all cells with the same rule
If there’s only one rule you want to dispose of, select any cell of that rule, open the Data Validation dialog box, select the Apply these changes to all the other cells with the same settings checkbox, click on the Clear All button, and then on the OK button.
Remove Data Validation from all cells on the sheet
Press Ctrl + A on the worksheet to select all the cells. Head to the Data Validation dialog box to use the Clear All button to remove all the Data Validation rules on the sheet.
Then hit the OK button.
How to Copy Data Validation to Other Cells
A plain copy & paste of a cell with Data Validation will paste the Data Validation rule and the value of the cell. To leave out the value and paste the rule, you can use the Validation option in Paste Special. If you don’t know how to use Paste Special, here’s what you need to do to copy Data Validation to other cells:
- To copy a particular Data Validation rule, select any cell with that rule and press the Ctrl + C keys to copy it.
- Now select the cell or the range where you want to paste the rule. Right-click the selection and click on Paste Special in the context menu.
- In the Paste Special dialog box, select the Validation radio button and then the OK
As a keyboard shortcut, press the Alt, E, S keys in succession to launch the Paste Special dialog box. Press the N key to select the Validation option and press the Enter key in place of clicking on the OK button.
The full keyboard shortcut after selecting the target cells becomes Alt, E, S, N, Enter in succession.
Data Validation will be copied to the target cells.
That was Data Validation for you, providing some form of sheet protection with data entry. Use the Data Validation rules to restrict what goes into a cell and expand the scope and usability by incorporating formulas. Two cheers to finding validation in our Excel life.
Introduction
Data validation is a feature in Excel used to control what a user can enter into a cell. For example, you could use data validation to make sure a value is a number between 1 and 6, make sure a date occurs in the next 30 days, or make sure a text entry is less than 25 characters.
Data validation can simply display a message to a user telling them what is allowed as shown below:
Data validation can also stop invalid user input. For example, if a product code fails validation, you can display a message like this:
In addition, data validation can be used to present the user with a predefined choice in a dropdown menu:
This can be a convenient way to give a user exactly the values that meet requirements.
Data validation controls
Data validation is implemented via rules defined in Excel’s user interface on the Data tab of the ribbon.
Important limitation
It is important to understand that data validation can be easily defeated. If a user copies data from a cell without validation to a cell with data validation, the validation is destroyed (or replaced). Data validation is a good way to let users know what is allowed or expected, but it is not a foolproof way to guarantee input.
Defining data validation rules
Data validation is defined in a window with 3 tabs: Settings, Input Message, and Error Alert:
The settings tab is where you enter validation criteria. There are a number of built-in validation rules with various options, or you can select Custom, and use your own formula to validate input as seen below:
The Input Message tab defines a message to display when a cell with validation rules is selected. This Input Message is completely optional. If no input message is set, no message appears when a user selects a cell with data validation applied. The input message has no effect on what the user can enter — it simply displays a message to let the user know what is allowed or expected.
The Error Alert Tab controls how validation is enforced. For example, when style is set to «Stop», invalid data triggers a window with a message, and the input is not allowed.
The user sees a message like this:
When style is set to Information or Warning, a different icon is displayed with a custom message, but the user can ignore the message and enter values that don’t pass validation. The table below summarizes behavior for each error alert option.
Alert Style | Behavior |
---|---|
Stop | Stops users from entering invalid data in a cell. Users can retry, but must enter a value that passes data validation. The Stop alert window has two options: Retry and Cancel. |
Warning | Warns users that data is invalid. The warning does nothing to stop invalid data. The Warning alert window has three options: Yes (to accept invalid data), No (to edit invalid data) and Cancel (to remove the invalid data). |
Information | Informs users that data is invalid. This message does nothing to stop invalid data. The Information alert window has 2 options: OK to accept invalid data, and Cancel to remove it. |
Data validation options
When a data validation rule is created, there are eight options available to validate user input:
Any Value — no validation is performed. Note: if data validation was previously applied with a set Input Message, the message will still display when the cell is selected, even when Any Value is selected.
Whole Number — only whole numbers are allowed. Once the whole number option is selected, other options become available to further limit input. For example, you can require a whole number between 1 and 10.
Decimal — works like the whole number option, but allows decimal values. For example, with the Decimal option configured to allow values between 0 and 3, values like .5, 2.5, and 3.1 are all allowed.
List — only values from a predefined list are allowed. The values are presented to the user as a dropdown menu control. Allowed values can be hardcoded directly into the Settings tab, or specified as a range on the worksheet.
Date — only dates are allowed. For example, you can require a date between January 1, 2018 and December 31 2021, or a date after June 1, 2018.
Time — only times are allowed. For example, you can require a time between 9:00 AM and 5:00 PM, or only allow times after 12:00 PM.
Text length — validates input based on number of characters or digits. For example, you could require code that contains 5 digits.
Custom — validates user input using a custom formula. In other words, you can write your own formula to validate input. Custom formulas greatly extend the options for data validation. For example, you could use a formula to ensure a value is uppercase, a value contains «xyz», or a date is a weekday in the next 45 days.
The settings tab also includes two checkboxes:
Ignore blank — tells Excel to not validate cells that contain no value. In practice, this setting seems to affect only the command «circle invalid data». When enabled, blank cells are not circled even if they fail validation.
Apply these changes to other cells with the same settings — this setting will update validation applied to other cells when it matches the (original) validation of the cell(s) being edited.
Note: You can also manually select all cells with data validation applied using Go To + Special, as explained below.
Simple drop down menu
You can provide a dropdown menu of options by hardcoding values into the settings box, or selecting a range on the worksheet. For example, to restrict entries to the actions «BUY», «HOLD», or «SELL» you can enter these values separated with commas as seen below:
When applied to a cell in the worksheet, the dropdown menu works like this:
Another way to supply values to a dropdown menu is to use a worksheet reference. For example, with sizes (i.e. small, medium, etc.) in the range F3:F6, you can supply this range directly inside the data validation settings window:
Note the range is entered as an absolute address to prevent it from changing as the data validation is applied to other cells.
Tip: Click the small arrow icon at the far right of the source field to make a selection directly on the worksheet so you don’t have to enter the range manually.
You can also use named ranges to specify values. For example, with the named range called «sizes» for F3:F7, you can enter the name directly in the window, starting with an equal sign:
Named ranges are automatically absolute, so they won’t change as the data validation is applied to different cells. If named ranges are new to you, this page has a good overview and a number of related tips.
Tip — if you use an Excel Table for dropdown values, Excel will expand or contract the table automatically when dropdown values are added or removed. In other words, Excel will automatically keep the dropdown in sync with values in the table as values are changed, added, or removed. If you’re new to Excel Tables, you can see a demo in this video on Table shortcuts.
Data validation with a custom formula
Data validation formulas must be logical formulas that return TRUE when input is valid and FALSE when input is invalid. For example, to allow any number as input in cell A1, you could use the ISNUMBER function in a formula like this:
=ISNUMBER(A1)
If a user enters a value like 10 in A1, ISNUMBER returns TRUE and data validation succeeds. If they enter a value like «apple» in A1, ISNUMBER returns FALSE and data validation fails.
To enable data validation with a formula, selected «Custom» in the settings tab, then enter a formula in the formula bar beginning with an equal sign (=) as usual.
Troubleshooting formulas
Excel ignores data validation formulas that return errors. If a formula isn’t working, and you can’t figure out why, set up dummy formulas to make sure the formula is performing as you expect. Dummy formulas are simply data validation formulas entered directly on the worksheet so that you can see what they return easily. The screen below shows an example:
Once you get the dummy formula working like you want, simply copy and paste it into the data validation formula area.
If this dummy formula idea is confusing to you, watch this video, which shows how to use dummy formulas to perfect conditional formatting formulas. The concept is exactly the same.
Data validation formula examples
The possibilities for data validation custom formulas are virtually unlimited. Here are a few examples to give you some inspiration:
To allow only 5 character values that begin with «z» you could use:
=AND(LEFT(A1)="z",LEN(A1)=5)
This formula returns TRUE only when a code is 5 digits long and starts with «z». The two circled values return FALSE with this formula.
To allow only a date within 30 days of today:
=AND(A1>TODAY(),A1<=(TODAY()+30))
To allow only unique values:
=COUNTIF(range,A1)<2
To allow only an email address
=ISNUMBER(FIND("@",A1)
Data validation to circle invalid entries
Once data validation is applied, you can ask Excel to circle previously entered invalid values. On the Data tab of the ribbon, click Data Validation and select «Circle Invalid Data»:
For example, the screen below shows values circled that fail validation with this custom formula:
=AND(LEFT(A1)="z",LEN(A1)=5)
Find cells with data validation
To find cells with data validation applied, you can use the Go To > Special dialog. Type the keyboard shortcut Control + G, then click the Special button. When the Dialog appears, select «Data Validation»:
Copy data validation from one cell to another
To copy validation from one cell to other cells. Copy the cell(s) normally that contain the data validation you want, then use Paste Special + Validation. Once the dialog appears, type «n» to select validation, or click validation with the mouse.
Note: you can use the keyboard shortcut Control + Alt + V to invoke Paste Special without the mouse.
Clear all data validation
To clear all data validation from a range of cells, make the selection, then click the Data Validation button on the Data tab of the ribbon. Then click the «Clear All» button:
To clear all data validation from a worksheet, select the entire worksheet, then, follow the same steps above.
See all How-To Articles
Data Validation is a tool in Excel that lets you restrict which entries are valid in a cell. Here are 10 rules and techniques to help you make the most out of Data Validation and its many features.
- Use Drop-Down Lists
- Data Validation Based on Another Cell
- ToolTips and Error Messages
- Options and Settings
- Date and Time Formats
- Set a Character Limit
- Validate Phone Numbers and Emails
- Custom Formulas
- Change or Remove Data Validation Rules
- Issues and Fixes
Use Drop-Down Lists
The most useful type of data validation is the drop-down list feature. For instructions on creating a drop-down list, see Create or Add a Drop-Down List in Excel and Google Sheets.
There are plenty of uses for drop-down lists and many ways to create them. For example, a simple yes/no drop-down list like the one below can be added as a quick and dependable indicator in a spreadsheet.
You can also use VBA to create a drop-down list in a cell. Enter this code in the VBA editor:
Sub DropDownListinVBA()
Range("A2").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="Orange,Apple,Mango,Pear,Peach"
End Sub
Dynamic Drop-Down Lists
- When you create a drop-down list based on a range of cells using a data validation rule, if the data in that specific range changes, then the values in the drop-down list also change.
- Go a step further with a cascading drop-down list based on the value that is selected in a different list. In the example below, the user has selected LG as the Phone Make. The list of Phone Models then shows only the LG models. If the user were to select either Apple or Samsung, then the list would change to show the relevant models for those makes of phone.
- An alternative method is to use an IF statement within the data validation feature to show a specific list that changes according to what the user selects. In the example below, if the user selects Show Fruit, then the fruit drop-down list is shown, whereas selecting Show Meat brings up the meat drop-down list.
Filter Data With a Drop-Down List
You can use Excel’s filter tool alongside a drop-down list for extended functionality.
- Filters and drop-down lists are similar and even use the same keyboard shortcut (CTRL + SHIFT + L). In a data validation context, the shortcut activates a drop-down menu.
- A drop-down list can also be used as a filter in Excel. It enables you to extract rows of data that match the entry in the drop-down list and return these rows to a separate area of the worksheet.
Drop-Down List Formatting and Display Tools
- If you want to create a drop-down list where the background color depends on the text selected, you can use Conditional Formatting to amend the background color when an item from the list is selected.
- When you create a drop-down list, the default value of the cell where you have placed the list is usually blank. It can be useful to pre-populate this cell with either a default value or a message to the user, such as Select…
- Once you’ve created a drop-down list, you can use the SORT and UNIQUE Functions to sort the drop-down list into alphabetical order.
- To make a drop-down list more readable, you can group a list of items by category (phone models in brand groups, for example).
AutoComplete Drop Down
AutoComplete is a useful feature of Excel in that it can reduce the number of characters you need to type in each cell. The standard data validation drop-down functionality does not support AutoComplete. However, you can learn here how to approximate autocomplete with a drop-down list. Then, when you start typing the first letters of an entry in the drop-down list, the rest of the entry automatically shows up.
Drop Down Populates Another Cell
- Selecting an item from a drop down can populate a different cell in Excel and Google Sheets. For example, in the graphic below, Patel is selected from the list, and the cell below is then populated with the value 34. You can learn how to do this by clicking here.
- Using a drop-down list, you can also insert a picture into another cell automatically.
Data Validation Based on Another Cell
When entering values in Excel, you can restrict the data that is entered into any range of cells based on text or a value held in another cell.
- When you create a drop-down list, you can write a custom input message that is seen on the screen when a cell is selected. This input message can also be referred to as a ToolTip.
- You can also customize the output (error alert) message that is returned to the user if invalid data is entered into a cell.
Options and Settings
- There are seven different data types you can select from the Allow box of the Validation criteria: Whole number, Decimal, List, Date, Time, Text length, and Custom.
- The Ignore blank option is only available if you are actually editing a cell that has that option switched off.
- You can also choose, when editing a data validation rule, whether or not to apply the changes to other cells with the same settings.
Date and Time Formats
You can use Data Validation to restrict the format entered into a cell to ensure it is a date, and also to restrict the entry to be set between a start date and an end date.
Set a Character Limit
In Excel, the number of characters allowed in a single cell is 32767. However, you can set your own character limit for a text cell.
Validate Phone Numbers and Emails
- You can use Data Validation to ensure that a phone number is entered correctly into Excel.
- You can also use Data Validation to ensure that an email address contains a @ sign and does not have any spaces or commas in it.
Custom Formulas
You can write a custom formula to make your own data validation rules. In the example below, the formula ensures that the data in a cell begins with certain text.
Custom Formula Examples
- You can use the INDIRECT Function in Excel in conjunction with a data validation drop-down list to create a cell reference from text.
- Use the ISNUMBER Function to check that the data inputted is in fact, a number. Data Validation has a built-in Whole number option, but you can generalize further with a custom formula.
- Use a the ISTEXT Function to check for text. The example below allows only text values in the cells with data validation applied.
- You can use a data validation drop down with the COUNTIF Function to count cells that meet certain criteria and return a total.
- COUNTIF is also useful for preventing users from entering duplicate values.
- A risk score matrix is a matrix that is used during risk assessment in order to calculate a risk value by inputting the likelihood and consequence of an event. You can use a data validation drop down in conjunction with the VLOOKUP and MATCH Functions to create a risk score matrix.
Change or Remove Data Validation Rules
- If you have a data validation rule set in Excel, you can find any restricted values by selecting Data validation in the Go To Special dialog box.
- You can copy data validation rules from one set of cells to another set of cells by using the Paste Special command (CTRL + ALT + V).
- If you already have rules set up in a worksheet, you can amend the validation rules should your requirements change.
- You can amend the contents of a drop-down list by following the instructions in this tutorial.
- You can easily update (change, extend, or have fewer items) a drop-down list by adding or deleting items from the list’s source range.
- If data validation on a range is no longer required, you can remove it.
- If you no longer require a drop-down list, you can easily remove the data validation settings by following the instructions in this tutorial.
Issues and Fixes
- If you have a value in Google Sheets that does not match the items in your drop-down list (an invalid item), you get a red triangle in the top left corner of the cell. To get rid of this triangle, you can follow the steps in this tutorial.
- There are a number of reasons why your data validation rule or drop-down list is not working correctly. You can troubleshoot these issues by referring to this tutorial.
- A mismatch error can occur when you run VBA code. The error stops your code from running completely and flags the error by means of a message box. One of the ways you can prevent this from happening is to use Data Validation on the spreadsheet to prevent the user from causing worksheet errors in the first place. Only allow them to enter values that don’t cause worksheet errors.
Skip to content
Мы рассмотрим, как выполнять проверку данных в Excel: создавать правила проверки для чисел, дат или текстовых значений, создавать списки проверки данных, копировать проверку данных в другие ячейки, находить недопустимые записи, исправлять и удалять проверку данных.
При настройке рабочей книги для пользователей часто может потребоваться контролировать ввод информации в определенные ячейки, чтобы убедиться, что все введенные данные точны и непротиворечивы. Кроме того, вы можете захотеть разрешить в ячейке только определенный тип данных, например числа или даты, или ограничить числа определенным диапазоном, а текст — заданной длиной. Возможно, вы даже захотите предоставить заранее определенный список допустимых значений, чтобы исключить возможные ошибки. Проверка данных Excel позволяет выполнять все эти действия во всех версиях Microsoft Excel 365, 2019, 2016, 20013, 2010 и более ранних версиях.
Что такое проверка данных в Excel?
Проверка данных Excel — это функция, которая ограничивает (проверяет) пользовательский ввод на рабочем листе. Технически вы создаете правило проверки, которое контролирует, какие данные можно вводить в определенную ячейку.
Вот лишь несколько примеров того, что может сделать проверка данных в Excel:
- Разрешить только числовые или текстовые значения в ячейке.
- Разрешить только числа в указанном диапазоне.
- Разрешить ввод данных определенной длины.
- Ограничить даты и время вне заданного диапазона.
- Ограничить записи выбором из раскрывающегося списка.
- Проверка вводимого на основе другой ячейки.
- Показать входное сообщение, когда пользователь выбирает ячейку.
- Показывать предупреждающее сообщение при вводе неверных данных.
- Найти неправильные записи в проверенных ячейках.
Например, вы можете настроить правило, которое ограничивает ввод данных 3-значными числами от 100 до 999. Если пользователь вводит что-то другое, Excel покажет предупреждение об ошибке, объясняющее, что было сделано неправильно:
Как сделать проверку данных в Excel
Чтобы добавить проверку данных в Excel, выполните следующие действия.
1. Откройте диалоговое окно «Проверка данных».
Напомним, где находится кнопка проверки данных в Excel. Выбрав одну или несколько ячеек для проверки, перейдите на вкладку «Данные» > группа «Работа с данными» и нажмите кнопку «Проверка данных».
2. Создайте правило проверки Excel.
На вкладке «Параметры» определите критерии проверки в соответствии с вашими потребностями. В критериях вы можете указать любое из следующего:
- Значения — введите числа в поля критериев, как показано на снимке экрана ниже.
- Ссылки на ячейки — создание правила на основе значения или формулы в другой ячейке.
- Формулы — позволяют выразить более сложные условия.
В качестве примера создадим правило, разрешающее пользователям вводить только целое число от 100 до 999:
Настроив правило проверки, нажмите кнопку «ОК», чтобы закрыть окно «Проверка вводимых значений», или переключитесь на другую вкладку, чтобы добавить подсказку по вводу и/или сообщение об ошибке.
3. Подсказка по вводу (необязательно).
Если вы хотите отобразить сообщение, объясняющее пользователю, какие данные разрешены в данной ячейке, откройте соответствующую вкладку и выполните следующие действия:
- Убедитесь, что установлен флажок Отображать подсказку при выборе ячейки.
- Введите заголовок и текст сообщения в соответствующие поля.
- Нажмите OK, чтобы закрыть диалоговое окно.
Как только пользователь выберет проверяемую ячейку, появится следующее сообщение, как на скриншоте ниже:
4. Отображение предупреждения об ошибке (необязательно)
В дополнение к входному сообщению вы можете отобразить одно из следующих предупреждений, когда в ячейку введены недопустимые данные.
Тип оповещения | Описание |
---|---|
Стоп (по умолчанию) | Самый строгий тип предупреждений, запрещающий пользователям вводить неверные данные. Вы нажимаете «Повторить», чтобы ввести другое значение, или «Отмена», чтобы удалить запись. |
Предупреждение | Предупреждает пользователей о том, что данные недействительны, но не препятствует их вводу. Вы нажимаете «Да», чтобы ввести недопустимое значение, «Нет», чтобы изменить его, или «Отмена», чтобы удалить запись. |
Информация | Наименее строгий тип оповещения, который информирует пользователей только о неверном вводе данных. Нажмите «ОК», чтобы ввести недопустимое значение, или «Отмена», чтобы удалить его из ячейки. |
Чтобы настроить пользовательское сообщение об ошибке, перейдите на вкладку «Сообщение об ошибке» и задайте следующие параметры:
- Установите флажок Выводить сообщение об ошибке (обычно установлен по умолчанию).
- В поле Вид выберите нужный тип оповещения.
- Введите заголовок и текст сообщения об ошибке в соответствующие поля.
- Нажмите ОК.
И теперь, если пользователь введет недопустимые значения, Excel отобразит специальное предупреждение с объяснением ошибки (как показано в начале этого руководства).
Примечание. Если вы не введете собственное сообщение, появится стандартное предупреждение Stop со следующим текстом: Это значение не соответствует ограничениям проверки данных, установленным для этой ячейки.
Как настроить ограничения проверки данных Excel
При добавлении правила проверки данных в Excel вы можете выбрать один из предопределенных параметров или указать новые критерии на основе собственной формулы. Ниже мы обсудим каждую из встроенных опций.
Как вы уже знаете, критерии проверки определяются на вкладке «Параметры» диалогового окна «Проверка данных» (вкладка «Данные» > «Проверка данных»).
В первую очередь нужно настроить проверку типа записываемых данных.
К примеру, чтобы ограничить ввод данных целым или десятичным числом, выберите соответствующий элемент в поле Тип данных. Затем выберите один из следующих критериев в поле Данные:
- Равно или не равно указанному числу
- Больше или меньше указанного числа
- Между двумя числами или вне, чтобы исключить этот диапазон чисел
Например, вот как выглядят ограничения по проверке данных Excel, которые допускают любое целое число больше 100:
Проверка даты и времени в Excel
Чтобы проверить даты, выберите «Дата» в поле «Тип данных», а затем выберите соответствующий критерий в поле «Значение». Существует довольно много предопределенных параметров на выбор: разрешить только даты между двумя датами, равные, большие или меньшие определенной даты и т. д.
Точно так же, чтобы проверить время, выберите Время в поле Значение, а затем определите необходимые критерии.
Например, чтобы разрешить только даты между датой начала в B1 и датой окончания в B2, примените это правило проверки даты Excel:
Разрешить только будни или выходные
Чтобы разрешить пользователю вводить даты только будних или выходных дней, настройте пользовательское правило проверки на основе функции ДЕНЬНЕД (WEEKDAY).
Если для второго аргумента установлено значение 2, функция возвращает целое число в диапазоне от 1 (понедельник) до 7 (воскресенье). Так, для будних дней (пн-пт) результат формулы должен быть меньше 6, а для выходных (сб и вс) — больше 5.
Таким образом, разрешить только рабочие дни:
=ДЕНЬНЕД( ячейка ; 2)<6
Разрешить только выходные :
=ДЕНЬНЕД( ячейка ; 2)>5
Например, чтобы разрешить ввод только рабочих дней в ячейки C2:C8, используйте следующую формулу:
=ДЕНЬНЕД(A2;2)<6
Проверить даты на основе сегодняшней даты
Во многих случаях может потребоваться использовать сегодняшнюю дату в качестве начальной даты допустимого диапазона дат. Чтобы получить текущую дату, используйте функцию СЕГОДНЯ , а затем добавьте к ней нужное количество дней, чтобы вычислить дату окончания временного периода.
Например, чтобы ограничить ввод данных через 6 дней (7 дней, включая сегодняшний день), мы можем использовать встроенное правило даты с критериями в виде формул:
- Выберите Дата в поле Тип данных
- Выберите в поле Значение – между
- В поле Начальная дата введите выражение =СЕГОДНЯ()
- В поле Конечная дата введите =СЕГОДНЯ() + 6
Аналогичным образом вы можете ограничить пользователей вводом дат до или после сегодняшней даты. Для этого выберите меньше или больше, чем в поле Значение, а затем введите =СЕГОДНЯ() в поле Начальная дата или Конечная дата соответственно.
Проверка времени на основе текущего времени
Чтобы проверить вводимые данные на основе текущего времени, используйте предопределенное правило времени с собственной формулой проверки данных. Для этого сделайте следующее:
В поле Тип данных выберите Время .
В поле Значение выберите «меньше», чтобы разрешить только время до текущего времени, или «больше», чтобы разрешить время после текущего времени.
В поле Время окончания или Время начала (в зависимости от того, какие критерии вы выбрали на предыдущем шаге) введите одну из следующих формул:
Чтобы проверить дату и время на основе текущей даты и времени:
=ТДАТА()
Чтобы проверить время на основе текущего времени, используйте выражение:
=ВРЕМЯ(ЧАС(ТДАТА());МИНУТЫ(ТДАТА());СЕКУНДЫ(ТДАТА()))
Проверка длины текста
Чтобы разрешить ввод данных определенной длины, выберите Длина текста в поле Тип данных и укажите критерии проверки в соответствии с вашей бизнес-логикой.
Например, чтобы ограничить ввод до 15 символов, создайте такое правило:
Примечание. Параметр «Длина текста» ограничивает количество символов, но не тип данных. Это означает, что приведенное выше правило разрешает как текст, так и числа до 15 символов или 15 цифр соответственно.
Список проверки данных Excel (раскрывающийся список)
Чтобы добавить для проверки вводимых данных раскрывающийся список элементов в ячейку или группу ячеек, выберите целевые ячейки и выполните следующие действия:
- Откройте диалоговое окно «Проверка данных» (вкладка «Данные» > «Проверка данных»).
- На вкладке «Настройки» выберите «Список» в поле «Тип данных».
- В поле Источник введите элементы списка проверки Excel, разделенные точкой с запятой. Например, чтобы ограничить пользовательский ввод тремя вариантами, введите Да; Нет; Н/Д.
- Убедитесь, что выбрана опция Список допустимых значений, чтобы стрелка раскрывающегося списка отображалась рядом с ячейкой.
- Нажмите ОК.
Выпадающий список проверки данных Excel будет выглядеть примерно так:
Примечание. Будьте осторожны с опцией «Игнорировать пустые ячейки», которая активна по умолчанию. Если вы создаете раскрывающийся список на основе именованного диапазона, в котором есть хотя бы одна пустая ячейка, установка этого флажка позволит ввести любое значение в проверенную ячейку. Во многих случаях это справедливо и для формул проверки данных: если ячейка, указанная в формуле, пуста, любое значение будет разрешено в проверяемой ячейке.
Другие способы создания списка проверки данных в Excel
Предоставление списков, разделенных точкой с запятой, непосредственно в поле «Источник» — это самый быстрый способ, который хорошо работает для небольших раскрывающихся списков, которые вряд ли когда-либо изменятся. В других сценариях можно действовать одним из следующих способов:
- Создать список проверки данных из диапазона ячеек.
- Создать динамический список проверки данных на основе именованного диапазона.
- Получить список проверки данных Excel из умной таблицы. Лучше всего то, что раскрывающийся список на основе таблицы является динамическим по своей природе и автоматически обновляется при добавлении или удалении элементов из этой таблицы.
Во всех этих случаях вы просто записываете соответствующую ссылку на диапазон либо элемент таблицы в поле Источник.
Разрешить только числа
В дополнение к встроенным правилам проверки данных Excel, обсуждаемым в этом руководстве, вы можете создавать собственные правила с собственными формулами проверки данных.
Удивительно, но ни одно из встроенных правил проверки данных Excel не подходит для очень типичной ситуации, когда вам нужно ограничить пользователей вводом только чисел в определенные ячейки. Но это можно легко сделать с помощью пользовательской формулы проверки данных, основанной на функции ЕЧИСЛО(), например:
=ЕЧИСЛО(C2)
Где C2 — самая верхняя ячейка диапазона, который вы хотите проверить.
Примечание. Функция ЕЧИСЛО допускает любые числовые значения в проверенных ячейках, включая целые числа, десятичные дроби, дроби, а также даты и время, которые также являются числами в Excel.
Разрешить только текст
Если вы ищете обратное — разрешить только текстовые записи в заданном диапазоне ячеек, то создайте собственное правило с функцией ЕТЕКСТ (ISTEXT), например:
=ЕТЕКСТ(B2)
Где B2 — самая верхняя ячейка выбранного диапазона.
Разрешить текст, начинающийся с определенных символов
Если все значения в определенном диапазоне должны начинаться с определенного символа или подстроки, выполните проверку данных Excel на основе функции СЧЁТЕСЛИ с подстановочным знаком:
=СЧЁТЕСЛИ(A2; » текст *»)
Например, чтобы убедиться, что все идентификаторы заказов в столбце A начинаются с префикса «AРТ-», «арт-», «Aрт-» или «aРт-» (без учета регистра), определите пользовательское правило с этой проверкой данных.
=СЧЁТЕСЛИ(A2;»АРТ-*»)
Формула проверки с логикой ИЛИ (несколько критериев)
В случае, если есть 2 или более допустимых префикса, добавьте несколько функций СЧЁТЕСЛИ, чтобы ваше правило проверки данных Excel работало с логикой ИЛИ:
=СЧЁТЕСЛИ(A2;»АРТ-*»)+СЧЁТЕСЛИ(A2;»АБВ-*»)
Проверка ввода с учетом регистра
Если регистр символов имеет значение, используйте СОВПАД (EXACT) в сочетании с функцией ЛЕВСИМВ, чтобы создать формулу проверки с учетом регистра для записей, начинающихся с определенного текста:
=СОВПАД(ЛЕВСИМВ(ячейка; число_символов); текст)
Например, чтобы разрешить только те коды заказов, которые начинаются с «AРТ-» (ни «арт-», ни «Арт-» не допускаются), используйте эту формулу:
=СОВПАД(ЛЕВСИМВ(A2;4);»АРТ-«)
В приведенной выше формуле функция ЛЕВСИМВ извлекает первые 4 символа из ячейки A2, а СОВПАД выполняет сравнение с учетом регистра с жестко заданной подстрокой (в данном примере «AРТ-«). Если две подстроки точно совпадают, формула возвращает ИСТИНА и проверка проходит успешно; в противном случае возвращается ЛОЖЬ и проверка завершается неудачно.
Разрешить только значения, содержащие определенный текст
Чтобы разрешить ввод значений, которые содержат определенный текст в любом месте ячейки (в начале, середине или конце), используйте функцию ЕЧИСЛО (ISNUMBER) в сочетании с НАЙТИ (FIND) или ПОИСК (SEARCH) в зависимости от того, хотите ли вы совпадение с учетом регистра или без учета регистра:
Проверка без учета регистра:
ЕЧИСЛО(ПОИСК( текст ; ячейка ))
Проверка с учетом регистра:
ЕЧИСЛО(НАЙТИ( текст ; ячейка ))
В нашем примере, чтобы разрешить только записи, содержащие текст «AР» в ячейках A2: A8, используйте одну из следующих формул, создав правило проверки в ячейке A2:
Без учета регистра:
=ЕЧИСЛО(ПОИСК(«ар»;A2))
С учетом регистра:
=ЕЧИСЛО(НАЙТИ(«АР»;A2))
Формулы работают по следующей логике:
Вы ищете подстроку «AР» в ячейке A2, используя НАЙТИ или ПОИСК, и оба возвращают позицию первого символа в подстроке. Если текст не найден, возвращается ошибка. Если поиск успешен и «АР» найден в ячейке, мы получаем номер позиции в тексте, где эта подстрока была найдена. Далее функция ЕЧИСЛО возвращает ИСТИНА, и проверка данных проходит успешно. В случае, если подстроку не удалось найти, результатом будет ошибка и ЕЧИСЛО возвращает ЛОЖЬ. Запись не будет разрешена в ячейке.
Разрешить только уникальные записи и запретить дубликаты
В ситуациях, когда определенный столбец или диапазон ячеек не должны содержать дубликатов, настройте пользовательское правило проверки данных, разрешающее только уникальные записи. Для этого мы можем использовать классическую формулу СЧЁТЕСЛИ для выявления дубликатов :
=СЧЁТЕСЛИ( диапазон ; самая верхняя_ячейка )<=1
Например, чтобы убедиться, что в ячейки с A2 по A8 вводятся только уникальные идентификаторы заказов, создайте настраиваемое правило со следующей формулой проверки данных:
=СЧЁТЕСЛИ($A$2:$A$8; A2)<=1
При вводе уникального значения формула возвращает ИСТИНА, и проверка проходит успешно. Если такое же значение уже существует в указанном диапазоне (счетчик больше 1), функция СЧЁТЕСЛИ возвращает ЛОЖЬ, и вводимые данные не проходят проверку.
Обратите внимание, что мы фиксируем диапазон абсолютными ссылками на ячейки (A$2:$A$8) и используем относительную ссылку для верхней ячейки (A2), чтобы формула корректно изменялась для каждой ячейки в проверяемом диапазоне.
Как отредактировать проверку данных в Excel
Чтобы изменить правило проверки Excel, выполните следующие действия:
- Выберите любую из проверенных ячеек.
- Откройте диалоговое окно «Проверка данных» (вкладка «Данные» > «Проверка данных»).
- Внесите необходимые изменения.
- Установите флажок Применить эти изменения ко всем другим ячейкам с теми же параметрами, чтобы скопировать внесенные вами изменения во все остальные ячейки с исходными критериями проверки.
- Нажмите OK, чтобы сохранить изменения.
Например, вы можете отредактировать список проверки данных Excel, добавив или удалив элементы из поля «Источник», и применить эти изменения ко всем другим ячейкам, содержащим тот же раскрывающийся список.
Как скопировать правило проверки данных Excel в другие ячейки
Если вы настроили проверку данных для одной ячейки и хотите проверить другие ячейки с теми же критериями, вам не нужно заново создавать правило с нуля.
Чтобы скопировать правило проверки в Excel, выполните следующие 4 быстрых шага:
- Выберите ячейку, к которой применяется правило проверки, и нажмите Ctrl + С , чтобы скопировать его.
- Выберите другие ячейки, которые вы хотите проверить. Чтобы выделить несмежные ячейки, нажмите и удерживайте клавишу Ctrl при выборе ячеек.
- Щелкните выделенный фрагмент правой кнопкой мыши, выберите «Специальная вставка» и выберите параметр «Условия на значения».
Либо используйте комбинацию клавиш Ctrl + Alt + V
, и затем — Н
.
- Нажмите ОК.
Подсказка. Вместо того, чтобы копировать проверку данных в другие ячейки, вы можете преобразовать свой набор данных в таблицу Excel. По мере добавления строк в таблицу Excel будет автоматически применять правило проверки к новым строкам.
Как найти ячейки с проверкой данных в Excel
Чтобы быстро найти все проверенные ячейки на текущем листе, перейдите на вкладку «Главная» > группа «Редактирование» и нажмите «Найти и выделить» > «Проверка данных» :
Это выберет все ячейки, к которым применены какие-либо правила проверки данных. Если необходимо, из этих выбранных ячеек вы можете удалить проверку.
Как убрать проверку данных в Excel
В целом, есть два способа удалить проверку в Excel: стандартный подход, разработанный Microsoft, и метод без мыши, разработанный фанатами Excel, которые никогда не отрывают руки от клавиатуры без крайней необходимости (например, чтобы выпить чашку кофе:)
Способ 1: Обычный способ отключить проверку данных
Обычно, чтобы удалить проверку данных на листах Excel, выполните следующие действия:
- Выберите ячейку (ячейки) с проверкой данных.
- На вкладке «Данные» нажмите кнопку «Проверка данных».
- На вкладке «Настройки» нажмите кнопку «Очистить все», а затем нажмите «ОК».
Советы:
- Чтобы удалить проверку данных из всех ячеек на текущем листе, используйте инструмент «Найти и выделить», чтобы выбрать все ячейки с проверкой.
- Чтобы удалить определенное правило проверки данных, выберите любую ячейку с этим правилом, откройте диалоговое окно «Проверка данных», установите флажок «Применить эти изменения ко всем другим ячейкам с такими же настройками» и нажмите кнопку «Очистить все».
Как видите, стандартный метод работает довольно быстро, но требует нескольких щелчков мышью, что, на мой взгляд, не имеет большого значения. Но если вы предпочитаете работать с клавиатурой, а не с мышью, вам может понравиться следующий подход.
Способ 2: Удалить правила проверки данных при помощи Специальной вставки
Изначально специальная вставка Excel предназначена для вставки определенных элементов скопированных ячеек. На самом деле она может делать гораздо больше полезных вещей. Среди прочего, он может быстро удалить правила проверки данных на листе. Вот как:
- Выберите пустую ячейку без проверки данных и нажмите
Ctrl + С
, чтобы скопировать ее в буфер обмена. - Выберите ячейки, в которых вы хотите отключить проверку данных.
- Нажмите
Ctrl + Alt + V
, и затемН
. Эта комбинация клавиш вызовет «Специальная вставка» > «Проверка данных». - Нажимаем ОК.
Советы по проверке данных в Excel
Теперь, когда вы знакомы с основами проверки данных в Excel, позвольте мне поделиться несколькими советами, которые могут сделать ваши правила намного более эффективными.
Проверка данных на основе другой ячейки
Вместо того, чтобы вводить значения непосредственно в поля критериев, вы можете ввести их в некоторые ячейки, а затем ссылаться на эти ячейки. Если вы решите позже изменить условия проверки, вы просто запишете новые значения на рабочем листе, не редактируя правило. Это сэкономит много времени.
Чтобы ввести ссылку на ячейку, либо введите ее в поле, перед которым стоит знак равенства, либо щелкните стрелку рядом с полем, а затем выберите ячейку с помощью мыши. Вы также можете щелкнуть в любом месте поля, а затем выбрать ячейку на листе.
Например, чтобы разрешить любое целое число, находящееся между 100 и 999, выберите критерии «минимум» и «максимум» в вкладке «Параметры» и введите в них адреса ячеек с этими числами:
Рис18
Вы также можете ввести формулу в ячейку, на которую указывает ссылка, и Excel проверит ввод на основе этой формулы.
Например, чтобы запретить пользователям вводить даты после сегодняшней даты, введите формулу =СЕГОДНЯ() в какую-нибудь ячейку, скажем, B1, а затем настройте правило проверки даты на основе этой ячейки:
Или вы можете ввести формулу =СЕГОДНЯ() непосредственно в поле Конечная дата, что будет иметь тот же эффект.
Правила проверки на основе формул
В ситуациях, когда невозможно определить желаемые критерии проверки на основе значения или ссылки на ячейку, вы можете выразить это с помощью формулы.
Например, чтобы ограничить ввод минимальным и максимальным значениями в существующем списке чисел, скажем, A1:A10, используйте следующие формулы:
=МИН($С$2:$С$10)
=МАКС($С$2:$С$10)
Обратите внимание, что мы фиксируем диапазон с помощью знака $ (абсолютная ссылка на ячейки), чтобы наше правило проверки Excel работало правильно для всех выбранных ячеек.
Как найти неверные данные на листе
Хотя Microsoft Excel позволяет применять проверку данных к ячейкам, в которых уже есть данные, он не уведомит вас, если некоторые из уже существующих значений не соответствуют критериям проверки.
Чтобы найти недействительные данные, которые попали в ваши рабочие листы до того, как вы добавили проверку данных, перейдите на вкладку «Данные» и нажмите «Проверка данных» > «Обвести неверные данные».
Это выделит все ячейки, которые не соответствуют критериям проверки.
Как только вы исправите неверную запись, отметка автоматически исчезнет. Чтобы удалить все отметки, перейдите на вкладку «Данные» и нажмите «Проверка данных» > «Удалить обводку неверных данных».
Как поделиться книгой с проверкой данных
Чтобы разрешить нескольким пользователям совместную работу над книгой, обязательно предоставьте к ней общий доступ после проверки данных.
После совместного использования книги ваши правила проверки данных продолжат работать, но вы не сможете ни изменить их, ни добавить новые правила.
Почему проверка данных Excel не работает?
Если проверка данных не работает должным образом на ваших листах, это, скорее всего, происходит по одной из следующих причин.
Проверка данных не работает для скопированных данных
Проверка данных в Excel предназначена для запрета ввода недопустимых данных непосредственно в ячейку, но не может помешать пользователям копировать недопустимые данные.
Хотя нет способа отключить клавиши копирования/вставки (кроме использования VBA), вы можете, по крайней мере, предотвратить копирование данных путем перетаскивания ячеек. Для этого выберите «Файл» > «Параметры» > «Дополнительно» > «Параметры редактирования» и снимите флажок «Включить маркер заполнения и перетаскивания ячеек».
Проверка данных Excel не активна
Кнопка «Проверка данных» не активна (выделена серым цветом), если вы вводите или изменяете данные в ячейке. Закончив редактирование ячейки, нажмите Enter или Esc, чтобы выйти из режима редактирования, а затем выполните проверку данных.
Проверка данных не может быть применена к защищенной или общей книге
Хотя существующие правила проверки продолжают работать в защищенных и общих книгах, невозможно изменить параметры проверки данных или настроить новые правила. Для этого сначала отмените общий доступ и/или снимите защиту с книги.
Неправильные формулы проверки данных
При проверке данных на основе формул в Excel необходимо проверить три важные вещи:
- Формула проверки не возвращает ошибок.
- Формула не ссылается на пустые ячейки.
- Используются правильные ссылки на ячейки.
Ручной пересчет формул включен
Если в Excel включен режим ручного расчета, невычисленные формулы могут помешать правильной проверке данных. Чтобы снова изменить параметр расчета Excel на автоматический, перейдите на вкладку «Формулы» > группу «Расчет», нажмите кнопку «Параметры расчета» и выберите «Автоматически».
Проверьте правильность формулы проверки данных
Для начала скопируйте формулу проверки в какую-нибудь ячейку, чтобы убедиться, что она не возвращает ошибку, такую как #Н/Д, #ЗНАЧ или #ДЕЛ/0!.
Если вы создаете пользовательское правило , формула должна возвращать логические значения ИСТИНА и ЛОЖЬ или приравненные к ним значения 1 и 0 соответственно.
Если вы используете критерий на основе формулы во встроенном правиле (как мы делали для проверки времени на основе текущего времени), он также может возвращать неправильное числовое значение.
Формула проверки данных не должна ссылаться на пустую ячейку
Если вы активируете опцию «Игнорировать пустые ячейки» при определении правила (обычно выбрано по умолчанию), то следите, чтобы ваши формулы или условия не ссылались на пустую ячейку.
В случае, когда одна или несколько ячеек, на которые есть ссылки в вашей формуле, пусты, то в проверяемой ячейке будет разрешено любое значение.
Абсолютные и относительные ссылки на ячейки в формулах проверки
При настройке правила проверки Excel на основе формулы помните, что все ссылки на ячейки в вашей формуле относятся к верхней левой ячейке в выбранном диапазоне.
Если вы создаете правило для нескольких ячеек и ваши критерии проверки содержат адреса конкретных ячеек , обязательно зафиксируйте ячейку в формуле при помощи абсолютной ссылки (со знаком $, например, $A$1), иначе ваше правило будет правильно работать только для первой ячейки.
Чтобы лучше проиллюстрировать это, рассмотрим следующий пример.
Предположим, вы хотите ограничить ввод данных в ячейках с A2 по A8 целыми числами от 100 (минимальное значение) до 999. Чтобы проще было при необходимости изменить критерии проверки, используем ссылки на ячейки с этими значениями, как показано на скриншоте ниже:
Это правило будет корректно выполняться только для первой ячейки диапазона – A2. Для ячейки A3 критерии максимума и минимума изменятся на E3 и F3. Поскольку эти ячейки пусты, то условие ввода теперь – любое число больше либо меньше нуля. Правда, символьные значения и дробные числа вы вводить не сможете, так как продолжает действовать ограничение на тип данных – целые числа.
Чтобы исправить формулу, просто введите «$» перед ссылками на столбцы и строки, чтобы зафиксировать их: =$E$2 и $F$2. Или используйте клавишу F4
для переключения между различными типами ссылок.
Вот как вы можете добавить и использовать проверку данных в Excel. Я благодарю вас за чтение и надеюсь ещё увидеть вас в нашем блоге!
The data validation in excel helps control the kind of input entered by a user in the worksheet. In other words, the input typed in a specific cell must comply with the criteria set for that cell. Data validation also allows providing instructions to the user about the input to be typed. The cell to which the data validation rule is applied is called a validated cell.
For example, the following data validation rules can be created in certain cells of Excel:
- A whole number between 1 (minimum) and 20 (maximum) is allowed.
- A date is allowed to be entered which is greater than September 15, 2000 (start date) or lesser than September 15, 2020 (end date).
- A text entry is allowed which matches any of the values (“yes,” “no,” and “cannot say”) of a drop-down list.
The pointers “a,” “b,” and “c” are the validating criteria defined for certain cells. If the input in these cells does not correspond to the respective pointer (a, b, or c), an error alert message is displayed by Excel.
Apart from setting the criteria, data validation in excel also allows to create a pre-defined range of inputs (drop-down list). In such cases, the user is asked to select the appropriate option (input) from this range. This ensures that all the data entries follow the same format.
Since the entries of all users are standardized, data validation brings about consistency and reduces errors. The “data validation” option is available in the “data tools” group of the Data tab of Excel.
Table of contents
- What is Data Validation in Excel?
- How to Use Data Validation in Excel?
- Example #1–“Data Validation” Window Explained
- Example #2–Decimal Number Validation
- Data Formats in Data validation
- The Different Validation Criteria
- The Different Error Alert Styles
- Purpose of Data Validation in Excel
- The Limitations of Data Validation in Excel
- Frequently Asked Questions
- Recommended Articles
- How to Use Data Validation in Excel?
How to Use Data Validation in Excel?
Let us consider some examples to understand the working of the data validation feature of Excel.
You can download this Data Validation Excel Template here – Data Validation Excel Template
Example #1–“Data Validation” Window Explained
The following image shows a list of numbers in column B. We want to perform the following tasks:
- Show how to create a data validation rule on the range B1:B4.
- Explain the tabs of the “data validation” window.
The steps explaining the creation of a data validation rule in Excel are listed as follows:
- Select the cells on which the data validation rule has to be created. So, select the range B1:B4.
- Click the data validation drop-down (in the “data tools” group) from the Data tab of Excel. The same is shown in the following image.
- Select “data validation” from the drop-down list.
- The “data validation” window appears, as shown in the following image.
- The first tab is “settings,” which contains the validation criteria. The same is shown in the succeeding image.
From the drop-down list under “allow,” one can select the data format allowed to the users. The drop-down list under “data” is used for defining the criteria.
For instance, if the input should be entered as a whole number, select the same from the drop-down list under “allow.” Once “whole number” is selected, one can choose the minimum and the maximum range between which this number is allowed to be entered.
Likewise, the desired validation criteria can be defined for the user.
Note: Refer to the topics “The Different Data Formats” and “The Different Validation Criteria” of this article for more information on adding validation criteria.
- The checkbox “ignore blank” is selected by default. This selection tells Excel to ignore the blank values.
- The second tab is “input message,” as shown in the succeeding image. One can enter the “title” and the “input message,” which are displayed when a validated cell is selected.
Note: An “input message” tells the user about the kind of input allowed in a validated cell. However, it is optional to add an input message. But, if one does add an input message, ensure that the checkbox of “show input message when cell is selected” is checked.
- The third tab is “error alert.” In this tab, one can enter the “title” and the “error message” that are displayed on typing invalid data in the validated cell.
From the “style” drop-down, one can select any of the three options, “stop,” “warning” or “information.” These are shown in the succeeding image.
Note 1: An “error message” is a customized message which tells the user that he/she has made an error while typing data in the validated cell. However, it is optional to add an error message. If an error message is added, ensure that the checkbox of “show error alert after invalid data is entered” is checked.
Note 2: In case an error message is not added, Excel displays the default error message, which states that restrictions have been defined for the validated cell.
Note 3: For more information on the error alert styles, refer to the topic “The Different Error Alert Styles” of this article.
- Once the entries in the three tabs, “settings,” “input message,” and “error alert” have been defined, click “Ok” in the “data validation” window.
The data validation excel rule is applied to the selected range B1:B4. Likewise, one can create a data validation rule by selecting either a single cell or a range of cells in Excel.
Note: For creating a data validation rule, it is mandatory to enter the validation criteria in the “settings” tab (step 5). However, it is optional to define the tabs “input message” (step 7) and “error alert” (step 8).
Example #2–Decimal Number Validation
Working on the data of example #1, we want to perform the following tasks:
- Create a data validation excel rule on cell B1. In this cell, a decimal number greater than or equal to zero is allowed to be entered.
- Define an input message which appears on selecting cell B1. The title should be “negative number detected” and the message should be “enter number greater than zero.”
The steps for performing the stated tasks are listed as follows:
Step 1: Select cell B1 which contains -2.5. From the Data tab of Excel, click the “data validation” drop-down. Select “data validation.”
Step 2: The “data validation” window appears, as shown in the following image. In the “settings” tab, select “decimal” under the “allow” drop-down.
Under the “data” drop-down, select “greater than or equal to.” In the box under “minimum,” enter “0” (without the double quotation marks).
Step 3: In the “input message” tab, select the checkbox of “show input message when cell is selected.”
In the box under “title,” type “negative number detected” without the double quotation marks. In the box “input message,” type “enter number greater than zero.” This should also be written without the double quotation marks. Click “Ok.”
The data validation rule is created on cell B1. To cross-check it, select the validated cell B1. The defined input message appears, as shown in the following image.
The number -2.5 was already there in cell B1 before the creation of the validation rule. This number is not deleted (from cell B1) even after creating a data validation rule.
However, in future, if a number is entered in cell B1, it must conform to the newly created rule. This implies that a decimal number greater than or equal to zero can be entered in cell B1. So, negative numbers are restricted in this cell. In case this rule is not complied with, Excel will display the default error alert.
Data Formats in Data validation
While entering data in a validated cell, there are certain formats that are allowed to the user. The rule creator (who is creating the data validation rule) can pick any of these formats based on which a validation rule can be created.
In the “settings” tab of the “data validation” window, the “allow” drop-down shows the following formats:
- Any value: This implies that no validation will be executed. In case a data validation rule is created and then “any value” is selected, the created validation rule is removed. However, the input message of the created validation rule can be viewed even after “any value” has been selected.
- Whole number: This requires that the user should enter a whole number in the validated cell.
- Decimal: This implies that the data format allowed in the validated cell is decimal numbers.
- List: This implies that the format allowed is a drop-down list. So, a drop-down list consisting of pre-defined values needs to be created. This drop-down list can be created in any of the following ways:
- Supply the values directly in the box under “source.”
- Provide the reference to the range (in the “source” box), which consists of the required values.
- Enter the name of the named range (in the “source” box), which begins with an “equal to” (=) sign.
- Date: This implies that the user can enter only a date in the validated cell.
- Time: This implies that a time value should be entered in the validated cell.
- Text Length: This helps fix the number of digits or text entered in a validated cell. For instance, the user can enter either numbers or text up to 5 digits or 5 characters respectively.
- Custom: This allows one to create a formula. This formula is used to validate (restrict) the input entered by the user. For instance, a formula can be entered to ensure that a text entry ends with certain characters, the text should be in uppercase or the entry must only be numeric, etc.
The Different Validation Criteria
Excel presents different criteria for validating data. The rule creator can select any of these criteria. Based on this selection, one can set the limits within which the input is allowed.
In the “settings” tab of the “data validation” dialog box, the drop-down under “data” shows the following validating criteria:
- Between: This implies that the input should be between the minimum and the maximum numbers specified.
- Not between: This implies that the input should not be between the minimum and the maximum numbers specified.
- Equal to: This implies that the input should be equal to the specified value. In other words, the input should be the same as the specified value.
- Not equal to: This implies that the input should not be equal to the specified value. In other words, the input should be different from the specified value.
- Greater than: This implies that the input should be greater than the minimum number specified.
- Less than: This implies that the input should be lesser than the maximum number specified.
- Greater than or equal to: This implies that the input should be greater than or equal to the minimum number specified.
- Less than or equal to: This implies that the input should be lesser than or equal to the maximum number specified.
The Different Error Alert Styles
There are different error alert styles in Excel. The rule creator can select any of these styles to notify the user that an error has been made while typing data in the validated cell.
In the “error alert” tab of the “data validation” window, the drop-down under “style” presents the following options:
- Stop: This stops the users from entering invalid data in the validated cell. With the “stop” style, the error alert message presents the following main options to the user:
- Retry– Clicking “retry” allows typing a new input.
- Cancel–Clicking “cancel” deletes the invalid input.
The “stop” style is the default error alert style of Excel.
- Warning: This warns the users that an invalid input has been entered. However, it does not stop the user from entering incorrect data. With the “warning” style, the user is presented with the following main options:
- Yes–Clicking “yes” makes Excel accept the invalid input.
- No–Clicking “no” allows typing a new input.
- Cancel–Clicking “cancel” deletes the invalid input.
- Information: This informs the user that the input entered is invalid. Like the “warning” style, this also does not stop the user from entering incorrect data. With the “information” style, the user is presented with the following main options:
- Ok–Clicking “Ok” makes Excel accept the invalid input.
- Cancel–Clicking “cancel” deletes the invalid input.
By selecting a style, its respective icon appears in the error alert message displayed by Excel.
For instance, with the “stop” style, the cross within the red circle is shown (in the error alert message) as the user enters invalid data. Likewise, with the “warning” and “information” styles, the exclamation mark (within a yellow triangle) and the “i” sign (within a blue circle) show up respectively.
Note: Apart from the main options listed (in the preceding pointers 1, 2, and 3), Excel also displays the “help” option in all the error alert messages, irrespective of the style selected.
Purpose of Data Validation in Excel
The objectives of data validation in excel are listed as follows:
- To restrict the users from entering unwanted or incorrect data values in the worksheet
- To sort and study the data obtained with the help of defined criteria
- To suggest the valid data format to the users through customized input messages (displayed when a validated cell is selected)
Excel Data validation is particularly helpful in the following situations:
- When the number of users is large and there is a possibility of entering inputs in different formats
- When the allowed entries need to be defined with a drop-down list
- When an error alert (warning message) needs to be displayed on entering invalid data
The Limitations of Data Validation in Excel
The limitations of data validation in excel are listed as follows:
- Data validation in excel does not prevent a user from copying an incorrect input from a non-validated cell to a validated cell. It can stop one from typing an incorrect input but not from copying the same. Hence, the purpose of data validation can become pointless if a user copies and pastes an invalid input.
- Excel Data validation cannot fully protect a worksheet from invalid data entries. If a user copies an incorrect input from a non-validated cell and pastes it in a validated cell, the validation rule in the latter cell is eliminated. As a result, the validation rule is absent on the copied data.
Frequently Asked Questions
1. Define data validation in Excel.
Data validation restricts (limits) the type of input entered by a user in the worksheet. One can set the criteria for a specific cell and ensure that the input typed (in that cell) complies with it.
For instance, in cell A1, one is allowed to type only a decimal number between 1.5 and 9.5. This is a data validation rule applied to cell A1 of the worksheet.
2. How can a data validation rule be edited in Excel?
Let us say that rule X has been applied to cells A1 and D1. We want to change this to rule Y for both the mentioned cells.
The steps to edit a data validation rule are listed as follows:
a. Select any of the cells to which rule X has been applied.
b. Select “data validation” from the “data validation” drop-down (in the “data tools” group) of the Data tab.
c. In the “settings” tab of the “data validation” window, enter the new criteria as per rule Y.
d. Select the checkbox of “apply these changes to all other cells with the same settings.” This ensures that rule Y is applied to both the cells A1 and D1.
e. Click “Ok.”
The rule Y has been applied to both cells A1 and D1.
Note: The new data validation rule can be applied to all the validated cells only if they all had the same validation criteria initially. In this case, the initial validation criterion (rule X) was the same for both the validated cells (A1 and D1).
3. How can a data validation rule be removed in Excel?
The steps to remove (delete) a data validation rule are listed as follows:
a. Select the validated cell.
b. From the “data validation” drop-down (in the “data tools” group) of the Data tab, select “data validation.”
c. The “data validation” window opens. In the “settings” tab, click “clear all” appearing at the bottom left side.
d. Click “Ok.”
The validation rule will be cleared from the selected cell (selected in step a).
Note: To remove the same validation rule applied to multiple cells, select the checkbox of “apply these changes to all other cells with the same settings.” Thereafter, click “clear all” followed by “Ok.”
Recommended Articles
This has been a guide to data validation in Excel. Here we discuss how to create a data validation rule in Excel along with examples and downloadable Excel templates. You may also look at these useful functions in Excel–
- How to Insert a Checkbox in Excel?A checkbox in excel is a square box used for presenting options (or choices) to the user to choose from.read more
- PERCENTILE Excel FunctionThe PERCENTILE function is responsible for returning the nth percentile from a supplied set of values. read more
- Paste Special ShortcutsPaste special in Excel allows you to paste partial aspects of the data copied. There are several ways to paste special in Excel, including right-clicking on the target cell and selecting paste special, or using a shortcut such as CTRL+ALT+V or ALT+E+S.read more
- Data Table – ExamplesA data table in excel is a type of what-if analysis tool that allows you to compare variables and see how they impact the result and overall data. It can be found under the data tab in the what-if analysis section.read more
Data Validation in Excel lets you control the data that can be entered in a cell. You can restrict the user to enter only a specified range of numbers or text or date.
You can also use data validation functionality to create an Excel drop down list (which is definitely one of the coolest and most powerful features in Excel)
Accessing Data Validation in Excel
Data Validation in Excel can be accessed through the Data tab in the Ribbon.
In most cases, there are three situations where you would want to use Data Validation in Excel:
- When you want to restrict data entry to certain numbers/text/dates. Data that does not meet the validation criteria is not allowed.
- When you want to inform user whenever out-of-range data is entered. However, all kinds of data entry is allowed.
- When you guide the user on what data to enter. All kinds of data entries are allowed.
Let’s us go through these situations one by one:
When you want to restrict data entry to certain numbers/text/dates
Data validation allows you to specify a condition for data entry in a cell/cells in Excel. Once specified, it does not allow the user to enter anything that is out of that specified range. This feature can be accessed by opening the data validation dialogue box and selecting the Settings option
In the drop-down list, you can choose the condition you want to apply for a range of cells
- Any Value – Allows any value to be entered in a cell.
- Whole Number – Allows only whole numbers to be entered, with additional conditions such as greater/less than, between/not between, equal to/not equal to.
- Decimal – Allows numbers with decimals to be entered, with additional conditions such as greater/less than, between/not between, equal to/not equal to.
- List – Creates a drop down by taking a list of items (through range selection or named range).
- Date – Allows dates (or its number value) to be entered, with additional conditions such as greater/less than, between/not between, equal to/not equal to.
- Time – Allows time (or its number value) to be entered, with additional conditions such as greater/less than, between/not between, equal to/not equal to.
- Text Length – Allows text with the condition on its length.
- Custom – Allows values that meets the specified criteria. For example, if I use the formula =A1>10, then only numbers greater than 10 are allowed in cell A1.
Whenever you enter any data in a cell that violates the specified condition, it shows an error.
When you want to inform user whenever out-of-range data is entered (all kinds of data entry is allowed)
While the earlier section was about restricting the user to a specified range while entering data, this section is about warning the user if any out-of-range data is entered. However, the data entry is still allowed. This can be enabled by changing the error message settings.
You can customize the error message by going to the Error Alert tab in the Data Validation dialogue box. There are three options:
- Stop Error – Displays the stop error and does not let user enter the data which is out of the specified range.
- Warning Error – Displays the warning error but lets user enter the data which is out of the specified range.
- Information Error – Displays the information error but lets user enter the data which is out of the specified range.
When You Guide the User on What Data to Enter (all kinds of data entry is allowed)
Suppose you have a list of employees and you want to get their joining date. There could be multiple formats to enter the date (such as 01/01/2014, or 01 Jan, 2014, or 1st Jan 2014). However, for the sake of consistency, it is better to get all the dates in one format. However, it is alright of people enter it in any other format, as capturing the data is of prime importance.
Here is how this can be done:
- Select any cell and then go to Data tab –> Data Validation
- In Data Validation dialogue box, select Input Message tab
- Ensure that ‘Show input message when cell is selected’ check box is selected
- In the Input message tab, enter Title (max 32 characters, optional) and Input Message (max 256 characters)
- Click ok. Now whenever you either click on the cell or select it using keyboard, it would display the message.
Caution: If you move the message box from its position, then all the message box will be shown at that position only. So it is safe not to move the message box.
Related Tutorials on Data Validation in Excel:
- Enable data entry only if a dependent cell is filled.
- Disguise numbers as text in a data validation drop down.
- Create a dependent validation drop down list.
- How to Remove Drop-Down List in Excel?
Microsoft Excel is a powerful tool and is widely useful too. It has various features to ease our work. One such feature is Data Validation. Now suppose you want the user to enter some specific values into the cells and for that, you need to set some pre-defined rules so that the user wouldn’t be able to enter other values and that’s where Data Validation steps in.
Data Validation gives you the control to receive particular inputs from users. We all have encountered using this feature in our day-to-day lives, one such example is while filling out forms in which the age cell will accept numbers similarly name column accepts text with limited characters, and data of birth will have years pre-defined to rule out the ineligible candidates.
Data Validation:
The data validation function can be found in the DATA tab from the excel ribbon(as seen in the picture below).
After clicking on the Data Validation, a menu appears.
Select Data Validation and a dialogue box appear.
There are 3 tabs in the dialogue box.
- Settings: This will help you to select the data type and the type of data that you want to be filled in the desired row or column.
- Input Message: This tab will help to let the user know about the constraints you’ve decided for the row/column. It will alert the user to input the right set of values.
- Error Alert: The error alert tab will help the user to know that they had entered invalid data.
Note: The data validation feature is not 100 percent reliable. If you will try to copy the data from cells which has no defined validation rules and then try to paste those cells to cells having data validation then all the validation part get vanished. Basically, validation rules get changed from the corresponding cell based on the copied cell content.
Example of Data Validation
Let’s take the example of filling a form. The form requires your name which has a limitation of 3-7 characters, it requires your date of birth and has a list of cities for the exam centre. Not considering all the other requirements as of now.
The form looks like this.
To apply data validation with a word limit of 3-7 characters for the Name cell.
Step 1: Select the empty cell in front of the Name.
Step 2: From the DATA tab in the ribbon, select Data Validation.
Step 3: A Dialogue box will appear.
Step 4: In the dialogue box from the setting tab, in the dropdown, select Text Length (as shown in the image below).
Step 5: We want our user to enter the name between 3-7 characters, So in the Minimum column we’ll write 3 and in the Maximum column we’ll write 7 and then click OK.
The Name row will now accept only text between 3-7 characters.
To use data validation as Date of Birth:
Step 6: Select the cell in front of Data of Birth in excel.
Step 7: Repeat steps 2 and 3.
Step 8: In this step, instead of selecting text length, you need to select Date (as shown in the image below).
If you want the user must be born between 1st January 2000 to 1st January 2021. Enter the Start date as 1st January 2000 and End date as 1st January 2021.
Step 9: Click OK.
Now, the Date of the Birth row will accept dates between 1st January 2000 to 1st January 2021.
To use data validation as a List:
Step 10: Select the empty cell in front of Exam Centre..
Step 11: Repeat steps 2 and 3.
Step 12: Select List (as shown in the image below).
You want to add “Kanpur”,”Agra”,”Aligarh”,”Lucknow”,”Varanasi” to the list.
Step 13: Add the names in the source column separated by a comma(,).
Step 14: Click OK.
The Exam centre cell will look like this.
You’ve successfully created a form with 3 requirements using Data Validation.