title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.Validation property (Excel) |
vbaxl10.chm144215 |
vbaxl10.chm144215 |
excel |
Excel.Range.Validation |
d1cad7e6-bbfa-e280-33e7-048733efc0bc |
05/11/2019 |
medium |
Range.Validation property (Excel)
Returns the Validation object that represents data validation for the specified range. Read-only.
Syntax
expression.Validation
expression A variable that represents a Range object.
Example
This example causes data validation for cell E5 to allow blank values.
Range("e5").Validation.IgnoreBlank = True
[!includeSupport and feedback]
Содержание
- Метод Validation.Add (Excel)
- Синтаксис
- Параметры
- Замечания
- Пример
- Поддержка и обратная связь
- Validation.Add method (Excel)
- Syntax
- Parameters
- Remarks
- Example
- Support and feedback
- Name already in use
- VBA-Docs / api / Excel.Validation.Add.md
- Refer to Named Ranges
- Workbook Named Range
- WorkSHEET Specific Named Range
- Referring to a Named Range
- Looping Through Cells in a Named Range
- About the Contributor
- Support and feedback
Метод Validation.Add (Excel)
Добавляет проверку данных в указанный диапазон.
Синтаксис
expression. Добавить (Type, AlertStyle, Operator, Formula1, Formula2)
Выражение Переменная, представляющая объект Проверки .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Тип | Обязательный | XlDVType | Тип проверки. |
AlertStyle | Необязательный | Variant | Стиль оповещения проверки. Может быть одной из следующих констант XlDVAlertStyle : xlValidAlertInformation, xlValidAlertStop или xlValidAlertWarning. |
Operator | Необязательный | Variant | Оператор проверки данных. Может быть одной из следующих констант XlFormatConditionOperator: xlBetween, xlEqual, xlGreaterEqual, xlLess, xlLess, xlLessEqual, xlNotBetween или xlNotEqual. |
Formula1 | Необязательный | Variant | Первая часть уравнения проверки данных. Значение не должно превышать 255 символов. |
Formula2 | Необязательный | Variant | Вторая часть уравнения проверки данных, если оператор имеет значение xlBetween или xlNotBetween (в противном случае этот аргумент игнорируется). |
Замечания
Метод Add требует различных аргументов в зависимости от типа проверки, как показано в следующей таблице.
Тип проверки | Аргументы |
---|---|
xlValidateCustom | Формула 1 является обязательной, формула 2 игнорируется. Формула 1 должна содержать выражение, которое имеет значение True , если ввод данных является допустимым, и False , если ввод данных недопустим. |
xlInputOnly | Используются AlertStyle, Formula1 или Formula2. |
xlValidateList | Формула 1 является обязательной, формула 2 игнорируется. Формула 1 должна содержать список значений с разделителями-запятыми или ссылку на этот список на листе. |
xlValidateWholeNumber, xlValidateDate, xlValidateDecimal, xlValidateTextLength или xlValidateTime | Необходимо указать одну из формул Formula1 или Formula2 , в противном случае можно указать оба варианта. |
Пример
В этом примере добавляется проверка данных в ячейку E5.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Validation.Add method (Excel)
Adds data validation to the specified range.
Syntax
expression.Add (Type, AlertStyle, Operator, Formula1, Formula2)
expression A variable that represents a Validation object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Type | Required | XlDVType | The validation type. |
AlertStyle | Optional | Variant | The validation alert style. Can be one of the following XlDVAlertStyle constants: xlValidAlertInformation, xlValidAlertStop, or xlValidAlertWarning. |
Operator | Optional | Variant | The data validation operator. Can be one of the following XlFormatConditionOperator constants: xlBetween, xlEqual, xlGreater, xlGreaterEqual, xlLess, xlLessEqual, xlNotBetween, or xlNotEqual. |
Formula1 | Optional | Variant | The first part of the data validation equation. Value must not exceed 255 characters. |
Formula2 | Optional | Variant | The second part of the data validation equation when Operator is xlBetween or xlNotBetween (otherwise, this argument is ignored). |
The Add method requires different arguments, depending on the validation type, as shown in the following table.
Validation type | Arguments |
---|---|
xlValidateCustom | Formula1 is required, Formula2 is ignored. Formula1 must contain an expression that evaluates to True when data entry is valid and False when data entry is invalid. |
xlInputOnly | AlertStyle, Formula1, or Formula2 are used. |
xlValidateList | Formula1 is required, Formula2 is ignored. Formula1 must contain either a comma-delimited list of values or a worksheet reference to this list. |
xlValidateWholeNumber, xlValidateDate, xlValidateDecimal, xlValidateTextLength, or xlValidateTime | One of either Formula1 or Formula2 must be specified, or both may be specified. |
Example
This example adds data validation to cell E5.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Name already in use
VBA-Docs / api / Excel.Validation.Add.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
Validation.Add method (Excel)
Adds data validation to the specified range.
expression.Add (Type, AlertStyle, Operator, Formula1, Formula2)
expression A variable that represents a Validation object.
Name | Required/Optional | Data type | Description |
---|---|---|---|
Type | Required | XlDVType | The validation type. |
AlertStyle | Optional | Variant | The validation alert style. Can be one of the following XlDVAlertStyle constants: xlValidAlertInformation, xlValidAlertStop, or xlValidAlertWarning. |
Operator | Optional | Variant | The data validation operator. Can be one of the following XlFormatConditionOperator constants: xlBetween, xlEqual, xlGreater, xlGreaterEqual, xlLess, xlLessEqual, xlNotBetween, or xlNotEqual. |
Formula1 | Optional | Variant | The first part of the data validation equation. Value must not exceed 255 characters. |
Formula2 | Optional | Variant | The second part of the data validation equation when Operator is xlBetween or xlNotBetween (otherwise, this argument is ignored). |
The Add method requires different arguments, depending on the validation type, as shown in the following table.
Validation type | Arguments |
---|---|
xlValidateCustom | Formula1 is required, Formula2 is ignored. Formula1 must contain an expression that evaluates to True when data entry is valid and False when data entry is invalid. |
xlInputOnly | AlertStyle, Formula1, or Formula2 are used. |
xlValidateList | Formula1 is required, Formula2 is ignored. Formula1 must contain either a comma-delimited list of values or a worksheet reference to this list. |
xlValidateWholeNumber, xlValidateDate, xlValidateDecimal, xlValidateTextLength, or xlValidateTime | One of either Formula1 or Formula2 must be specified, or both may be specified. |
This example adds data validation to cell E5.
Источник
Refer to Named Ranges
Ranges are easier to identify by name than by A1 notation. To name a selected range, click the name box at the left end of the formula bar, type a name, and then press ENTER.
Note There are two types of named ranges: Workbook Named Range and WorkSHEET Specific Named Range.
Workbook Named Range
A Workbook Named Range references a specific range from anywhere in the workbook (it applies globally).
How to Create a Workbook Named Range:
As explained above, it is usually created entering the name into the name box to the left end of the formula bar. Note that no spaces are allowed in the name.
WorkSHEET Specific Named Range
A WorkSHEET Specific Named Range refers to a range in a specific worksheet, and it is not global to all worksheets within a workbook. Refer to this named range by just the name in the same worksheet, but from another worksheet you must use the worksheet name including «!» the name of the range (example: the range «Name» «=Sheet1!Name»).
The benefit is that you can use VBA code to generate new sheets with the same names for the same ranges within those sheets without getting an error saying that the name is already taken.
How to Create a WorkSHEET Specific Named Range:
- Select the range you want to name.
- Click on the «Formulas» tab on the Excel Ribbon at the top of the window.
- Click «Define Name» button in the Formula tab.
- In the «New Name» dialogue box, under the field «Scope» choose the specific worksheet that the range you want to define is located (i.e. «Sheet1»)- This makes the name specific to this worksheet. If you choose «Workbook» then it will be a WorkBOOK name).
Example, of WorkSHEET Specific Named Range: Selected range to name are A1:A10
Chosen name of range is «name» within the same worksheet refer to the named name mere by entering the following in a cell «=name», from a different worksheet refer to the worksheet specific range by included the worksheet name in a cell «=Sheet1!name».
Referring to a Named Range
The following example refers to the range named «MyRange» in the workbook named «MyBook.xls.»
The following example refers to the worksheet-specific range named «Sheet1!Sales» in the workbook named «Report.xls.»
To select a named range, use the GoTo method, which activates the workbook and the worksheet and then selects the range.
The following example shows how the same procedure would be written for the active workbook.
Sample code provided by: Dennis Wallentin, VSTO & .NET & Excel
This example uses a named range as the formula for data validation. This example requires the validation data to be on Sheet 2 in the range A2:A100. This validation data is used to validate data entered on Sheet 1 in the range D2:D10.
Looping Through Cells in a Named Range
The following example loops through each cell in a named range by using a For Each. Next loop. If the value of any cell in the range exceeds the value of Limit , the cell color is changed to yellow.
About the Contributor
Dennis Wallentin is the author of VSTO & .NET & Excel, a blog that focuses on .NET Framework solutions for Excel and Excel Services. Dennis has been developing Excel solutions for over 20 years and is also the coauthor of «Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA and .NET (2nd Edition).»
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
One thing I often found frustrating with VBA is the lack of any easy way to see the values in a range object.
I often use Debug.Print when debugging my VBA and I’d love to just be able to Debug.Print a range like you can with other variables.
But because a range is an object, not a variable, you can’t do that.
One way to see what’s in a range is to step through your code (pressing F8) and when the range is set, you can check the values in the range in the Locals window.
Our range looks like this
How To Open The Locals Window
In the VBA editor go to the View menu and click on Locals Window.
Each time F8 is pressed one line of VBA is executed. When the range MyRange is set, you can see that values appear for it in the Locals window.
By examining the MyRange object you can drill down to see the values in it.
Your browser does not support the video tag.
You can also set a Watch on the MyRange object to examine it in the Watch window, but this is essentially doing the same thing as examining it in the Locals window.
Using both Locals and Watch windows require you to step though code and examine values as the code executes.
If you want to just let the VBA run and see the values in the range printed out to the Immediate window, you need to write some code to do this.
How To Open The Immediate Window
In the VBA editor press CTRL+G, or go to the View menu and click on Immediate Window.
Print Values in Range One by One (Unformatted)
The code shown below will go through each cell in the range and print its value to the Immediate window.
However because we are printing one value at a time, it doesn’t really give you a feel for the structure of the range. That is in this case, that there are 4 values per row/line.
Your browser does not support the video tag.
Print Values in Range Row by Row (Formatted)
This next sub stores each value in a row to an array, and then prints out all of these values using the JOIN function to create a string with values separated by a comma.
More on VBA String Functions
This formatted output gives a better representation of the actual structure of your range.
In this format, you can also use the output to write data to a CSV file.
Download Sample Workbook
Enter your email address below to download the workbook containing all the code from this post.
By submitting your email address you agree that we can email you our Excel newsletter.
The full VBA code is shown below.
Use the Add method of the DataValidation property of the Range object.
Name | Value |
---|---|
xlValidateCustom | 7 |
xlValidateDate | 4 |
xlValidateDecimal | 2 |
xlValidateInputOnly | 0 |
xlValidateList | 3 |
xlValidateTextLength | 6 |
xlValidateTime | 5 |
xlValidateWholeNumber | 1 |
Use the AlertStyle parameter to specify the style of the alert warning dialog.
Name | Value |
---|---|
xlValidAlertInformation | 3 |
xlValidAlertStop | 1 |
xlValidAlertWarning | 2 |
Use the Operator parameter together with the Formula parameters to specify a rule.
Name | Value |
---|---|
xlBetween | 1 |
xlEqual | 3 |
xlGreater | 5 |
xlGreaterEqual | 7 |
xlLess | 6 |
xlLessEqual | 8 |
xlNotBetween | 2 |
xlNotEqual | 4 |
Specify the error title and error message of the alert dialog in the DataValidation property itself (see code below).
This code below relates to the table shown above. Column A’s validation allow dates, but not in the past. Columns C and D have been given drop down lists. Each list has a named source – Properties and Issue_Type.
With Range("A2:A10").Validation .Add Type:=xlValidateDate, Operator:=xlGreaterEqual, Formula1:=Date, _ AlertStyle:=xlValidAlertStop .ErrorTitle = "ReportingDate" .ErrorMessage = "You cannot enter a reporting date as a date in the past" End With With Range("C2:C10").Validation .Add Type:=xlValidateList, Operator:=xlBetween, Formula1:="=Properties", _ AlertStyle:=xlValidAlertStop .ErrorTitle = "Property" .ErrorMessage = "Please select a property from the list" End With With Range("D2:D10").Validation .Add Type:=xlValidateList, Operator:=xlBetween, Formula1:="=Issue_Type", _ AlertStyle:=xlValidAlertStop .ErrorTitle = "IssueType" .ErrorMessage = "Please select an Issue Type from the list" End With
Goat movie ratings
It’s Wilde Week in goatville. The Wildes are like the Oscars, but for goat movies.
You have a worksheet like this:
The data starts in row 9. Each record has four fields:
- Movie title
- Genre (romance, action, or scifi)
- Average critic rating, from 1 to 5
- Average viewer rating, from 1 to 5
The data is not reliable, unfortunately. You can see a few errors in the screen shot.
You want to compute the stuff in rows 4 to 6:
- Number of valid records
- Number of invalid records
- Number of records where the viewer rating is higher than the critic rating.
You can download a solution.
Pattern
In the previous lesson on normalization, the pattern was something like this:
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Process the data
Let’s add one more line. It will be the final shiny on this pattern.
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Validate the data
- Process the data
So, after we normalize the fields in a record, we’ll check them for errors.
M0000t!
All but validation
Here’s the code, except for the validation.
- ‘Set up the Range.
- Set rMovieRecords = Range(Cells(9, 1), Cells(9, 1).End(xlToRight).End(xlDown))
- sCountAllRecords = rMovieRecords.Rows.Count
- ‘Initialize
- sCountValidRecords = 0
- sCountInvalidRecords = 0
- sCountViewerMoreThanCritic = 0
- For sRecordNumber = 1 To sCountAllRecords
- ‘Read the current record
- tTitle = rMovieRecords.Cells(sRecordNumber, TITLE_COLUMN)
- tGenre = rMovieRecords.Cells(sRecordNumber, GENRE_COLUMN)
- sCriticRating = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
- sViewerRating = rMovieRecords.Cells(sRecordNumber, VIEWER_RATING_COLUMN)
- ‘Normalize title and genre
- tTitle = Trim(tTitle)
- tGenre = LCase(Trim(tGenre))
- ‘Process
- sCountValidRecords = sCountValidRecords + 1
- If sViewerRating > sCriticRating Then
- sCountViewerMoreThanCritic = sCountViewerMoreThanCritic + 1
- End If
- Next sRecordNumber
- ‘Output
- Cells(4, 2) = sCountValidRecords
- Cells(5, 2) = sCountInvalidRecords
- Cells(6, 2) = sCountViewerMoreThanCritic
There’s a For
loop to run through the data:
- sCountAllRecords = rMovieRecords.Rows.Count
- …
- For sRecordNumber = 1 To sCountAllRecords
- …
- Next sRecordNumber
Inside the loop, the first thing is to grab the fields for the current record. Here’s the pseudocode:
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Process the data
Here’s the real code.
- For sRecordNumber = 1 To sCountAllRecords
- ‘Read the current record
- tTitle = rMovieRecords.Cells(sRecordNumber, TITLE_COLUMN)
- tGenre = rMovieRecords.Cells(sRecordNumber, GENRE_COLUMN)
- sCriticRating = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
- sViewerRating = rMovieRecords.Cells(sRecordNumber, VIEWER_RATING_COLUMN)
- …
- Next sRecordNumber
The next step is to normalize.
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Process the data
The code:
- For sRecordNumber = 1 To sCountAllRecords
- …
- ‘Normalize title and genre
- tTitle = Trim(tTitle)
- tGenre = LCase(Trim(tGenre))
- …
- Next sRecordNumber
The last step is processing.
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Process the data
The code:
- For sRecordNumber = 1 To sCountAllRecords
- …
- ‘Process
- sCountValidRecords = sCountValidRecords + 1
- If sViewerRating > sCriticRating Then
- sCountViewerMoreThanCritic = sCountViewerMoreThanCritic + 1
- End If
- Next sRecordNumber
The flag pattern for validation
Let’s add the validation. We have three fields to check:
- Genre (romance, action, or scifi)
- Average critic rating, from 1 to 5
- Average viewer rating, from 1 to 5
We want to do the processing only if all of the fields have valid data. If there’s an error in any field of a record, we want to ignore the record.
For that, we can use the flag pattern again.
Pattern
Flag
A variable that summarizes the results of a bunch of code.
Here’s what the code will be like:
- tDataOk = «yes»
- If field 1 is bad Then
- tDataOk = «no»
- EndIf
- If field 2 is bad Then
- tDataOk = «no»
- EndIf
- If field 3 is bad Then
- tDataOk = «no»
- EndIf
- If tDataOk = «yes» Then
- Processing
- EndIf
If any of the fields are bad, then tDataOk
will be «no» by the time we get to line 11: If tDataOk = "yes" Then
.
Validating genre
Genre is a string field with three valid values. Here’s code that will validate it:
- If tGenre <> «romance» And tGenre <> «action» And tGenre <> «scifi» Then
- tDataOk = «no»
- End If
Ray
What if the genre is «Romance» instead of «romance». That If
won’t pick it up.
Reflect
Is Ray right? Why, or why not?
If you were logged in as a student, the lesson would pause here, and you’d be asked to type in a response. If you want to try that out, ask for an account on this site.
Georgina
We already normalized the data, so «Romance» will have been converted to «romance».
- tGenre = LCase(Trim(tGenre))
Validating ratings
Here’s code to validate the critic rating:
- tCriticRatingIn = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
- …
- ‘Check critic rating
- ‘Is it a number?
- If Not IsNumeric(tCriticRatingIn) Then
- ‘Not a number
- tDataOk = «no»
- Else
- ‘It is a number
- ‘Copy value to a numeric variable
- sCriticRating = tCriticRatingIn
- ‘Range check
- If sCriticRating < 1 Or sCriticRating > 5 Then
- tDataOk = «no»
- End If
- End If
First, we put the field’s value into a string variable (line 1). If we put it straight into a numeric variable, the program will crash if the cell contains something like «fish».
Then we check whether it’s numeric (line 5). If it isn’t, set the flag, and that’s it.
If tCriticRatingIn
is a number, then copy it to the numeric variable sCriticRating
(line 11). Then do a range check.
All the code
Let’s put everything together. Check that this makes sense.
- ‘Set up the Range.
- Set rMovieRecords = Range(Cells(9, 1), Cells(9, 1).End(xlToRight).End(xlDown))
- sCountAllRecords = rMovieRecords.Rows.Count
- ‘Initialize
- sCountValidRecords = 0
- sCountInvalidRecords = 0
- sCountViewerMoreThanCritic = 0
- For sRecordNumber = 1 To sCountAllRecords
- ‘Read the current record
- tTitle = rMovieRecords.Cells(sRecordNumber, TITLE_COLUMN)
- tGenre = rMovieRecords.Cells(sRecordNumber, GENRE_COLUMN)
- tCriticRatingIn = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
- tViewerRatingIn = rMovieRecords.Cells(sRecordNumber, VIEWER_RATING_COLUMN)
- ‘Normalize title and genre
- tTitle = Trim(tTitle)
- tGenre = LCase(Trim(tGenre))
- ‘Validate
- tDataOk = «yes»
- ‘Check genre
- If tGenre <> «romance» And tGenre <> «action» And tGenre <> «scifi» Then
- tDataOk = «no»
- End If
- ‘Check critic rating
- If Not IsNumeric(tCriticRatingIn) Then
- tDataOk = «no»
- Else
- sCriticRating = tCriticRatingIn
- If sCriticRating < 1 Or sCriticRating > 5 Then
- tDataOk = «no»
- End If
- End If
- ‘Check viewer rating
- If Not IsNumeric(tViewerRatingIn) Then
- tDataOk = «no»
- Else
- sViewerRating = tViewerRatingIn
- If sViewerRating < 1 Or sViewerRating > 5 Then
- tDataOk = «no»
- End If
- End If
- ‘Process
- If tDataOk = «yes» Then
- ‘Data is valid.
- sCountValidRecords = sCountValidRecords + 1
- If sViewerRating > sCriticRating Then
- sCountViewerMoreThanCritic = sCountViewerMoreThanCritic + 1
- End If
- Else
- sCountInvalidRecords = sCountInvalidRecords + 1
- End If
- Next sRecordNumber
- ‘Output
- Cells(4, 2) = sCountValidRecords
- Cells(5, 2) = sCountInvalidRecords
- Cells(6, 2) = sCountViewerMoreThanCritic
Check out lines 51 and 52. They let you count the number of invalid records.
Now you know how to analyze a Range
.
- For each record:
- Grab the record’s data from the Range
- Normalize the data
- Validate the data
- Process the data
M0000t! If you understood everything here, give yourself a pat on the back. This is getting to be real data analysis.
M0000ty, m0000ty, m0000t, m0000t!