Range validation vba excel

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]

Содержание

  1. Метод Validation.Add (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Validation.Add method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. Name already in use
  14. VBA-Docs / api / Excel.Validation.Add.md
  15. Refer to Named Ranges
  16. Workbook Named Range
  17. WorkSHEET Specific Named Range
  18. Referring to a Named Range
  19. Looping Through Cells in a Named Range
  20. About the Contributor
  21. 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:

  1. Select the range you want to name.
  2. Click on the «Formulas» tab on the Excel Ribbon at the top of the window.
  3. Click «Define Name» button in the Formula tab.
  4. 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

Range in Excel

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.

VBA Code to print range values

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.

VBA Code to print formatted range values

Running VBA code to print formatted values in range

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:

Movie data

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.

Goat

​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:

  1. tDataOk = «yes»
  2. If field 1 is bad Then
  3.     tDataOk = «no»
  4. EndIf
  5. If field 2 is bad Then
  6.     tDataOk = «no»
  7. EndIf
  8. If field 3 is bad Then
  9.     tDataOk = «no»
  10. EndIf
  11. If tDataOk = «yes» Then
  12.     Processing
  13. 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

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

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:

  1. tCriticRatingIn = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
  2. ‘Check critic rating
  3. ‘Is it a number?
  4. If Not IsNumeric(tCriticRatingIn) Then
  5.     ‘Not a number
  6.     tDataOk = «no»
  7. Else
  8.     ‘It is a number
  9.     ‘Copy value to a numeric variable
  10.     sCriticRating = tCriticRatingIn
  11.     ‘Range check
  12.     If sCriticRating < 1 Or sCriticRating > 5 Then
  13.         tDataOk = «no»
  14.     End If
  15. 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.

  1. ‘Set up the Range.
  2. Set rMovieRecords = Range(Cells(9, 1), Cells(9, 1).End(xlToRight).End(xlDown))
  3. sCountAllRecords = rMovieRecords.Rows.Count
  4. ‘Initialize
  5. sCountValidRecords = 0
  6. sCountInvalidRecords = 0
  7. sCountViewerMoreThanCritic = 0
  8. For sRecordNumber = 1 To sCountAllRecords
  9.     ‘Read the current record
  10.     tTitle = rMovieRecords.Cells(sRecordNumber, TITLE_COLUMN)
  11.     tGenre = rMovieRecords.Cells(sRecordNumber, GENRE_COLUMN)
  12.     tCriticRatingIn = rMovieRecords.Cells(sRecordNumber, CRITIC_RATING_COLUMN)
  13.     tViewerRatingIn = rMovieRecords.Cells(sRecordNumber, VIEWER_RATING_COLUMN)
  14.  
  15.     ‘Normalize title and genre
  16.     tTitle = Trim(tTitle)
  17.     tGenre = LCase(Trim(tGenre))
  18.  
  19.     ‘Validate
  20.     tDataOk = «yes»
  21.     ‘Check genre
  22.     If tGenre <> «romance» And tGenre <> «action» And tGenre <> «scifi» Then
  23.         tDataOk = «no»
  24.     End If
  25.     ‘Check critic rating
  26.     If Not IsNumeric(tCriticRatingIn) Then
  27.         tDataOk = «no»
  28.     Else
  29.         sCriticRating = tCriticRatingIn
  30.         If sCriticRating < 1 Or sCriticRating > 5 Then
  31.             tDataOk = «no»
  32.         End If
  33.     End If
  34.     ‘Check viewer rating
  35.     If Not IsNumeric(tViewerRatingIn) Then
  36.         tDataOk = «no»
  37.     Else
  38.         sViewerRating = tViewerRatingIn
  39.         If sViewerRating < 1 Or sViewerRating > 5 Then
  40.             tDataOk = «no»
  41.         End If
  42.     End If
  43.  
  44.     ‘Process
  45.     If tDataOk = «yes» Then
  46.         ‘Data is valid.
  47.         sCountValidRecords = sCountValidRecords + 1
  48.         If sViewerRating > sCriticRating Then
  49.             sCountViewerMoreThanCritic = sCountViewerMoreThanCritic + 1
  50.         End If
  51.     Else
  52.         sCountInvalidRecords = sCountInvalidRecords + 1
  53.     End If
  54.  
  55. Next sRecordNumber
  56.  
  57. ‘Output
  58. Cells(4, 2) = sCountValidRecords
  59. Cells(5, 2) = sCountInvalidRecords
  60. 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.

Goat

​M0000ty, m0000ty, m0000t, m0000t!

Like this post? Please share to your friends:
  • Range text vba word
  • Range sort in excel vba
  • Range select in vba for excel
  • Range pastespecial vba excel
  • Range paste vba word