title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Validation.Add method (Excel) |
vbaxl10.chm532073 |
vbaxl10.chm532073 |
excel |
Excel.Validation.Add |
e02c9d5e-dbb1-7d37-d112-0c60e7a7ff03 |
05/18/2019 |
medium |
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). |
Remarks
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.
With Range("e5").Validation .Add Type:=xlValidateWholeNumber, _ AlertStyle:= xlValidAlertStop, _ Operator:=xlBetween, Formula1:="5", Formula2:="10" .InputTitle = "Integers" .ErrorTitle = "Integers" .InputMessage = "Enter an integer from five to ten" .ErrorMessage = "You must enter a number from five to ten" End With
[!includeSupport and feedback]
based on examples above and examples found on other sites, I created a generic procedure and some examples.
'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim InputTitle As String: InputTitle = "Please Select a Value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a Value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True 'Show input message on hover
Dim ShowError As Boolean: ShowError = True 'Show error message on error
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub
'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle: XlDVAlertStyle https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
Optional InputTitle As String = "", _
Optional InputMessage As String = "", _
Optional ErrorTitle As String = "", _
Optional ErrorMessage As String = "", _
Optional ShowInput As Boolean = True, _
Optional ShowError As Boolean = True, _
Optional ValidationType As XlDVType = xlValidateList, _
Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
Optional ValidationFormula1 As Variant = "", _
Optional ValidationFormula2 As Variant = "")
With CreateInRange.Validation
.Delete
.Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = InputTitle
.ErrorTitle = ErrorTitle
.InputMessage = InputMessage
.ErrorMessage = ErrorMessage
.ShowInput = ShowInput
.ShowError = ShowError
End With
End Sub
'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
Dim CreateOnSheetName As String: CreateOnSheetName = "Test" 'The sheet containing the dropdown
Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName)
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName)
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim FieldName As String: FieldName = "Testing Dropdown"
Dim InputTitle As String: InputTitle = "Please Select a value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True
Dim ShowError As Boolean: ShowError = True
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
Содержание
- Метод 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
- VBA Drop Down List (Data Validation)
- Creating a Drop Down List Using VBA
- Populate a Drop Down List From a Named Range in VBA
- Removing the Drop Down List
- VBA Coding Made Easy
- VBA Code Examples Add-in
Метод 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.
Источник
VBA Drop Down List (Data Validation)
In this Article
This tutorial will demonstrate how to use Data Validation to work with drop-down lists in Excel using VBA.
Excel Data Validation allows you to limit what value(s) may be entered in a cell or range. You can limit entries to positive integers, text, dates, and much more. In this tutorial, we are going to look at how to create a Data Validation Drop-Down List in a cell using VBA.
Note: An alternative to a Data Validation Drop-Down list is a ListBox object. ListBoxes can be added to Excel worksheets. ListBoxes can trigger macros that run every time a ListBox value is changed. ListBoxes are also used in VBA Userforms.
Creating a Drop Down List Using VBA
We have the text Fruit in cell A1, and we are going to create a drop-down list in cell A2, with five entries.
We will use the Validation.Add method and specify that the Type parameter is xlValidateList. You can add the specific items you would like in your list using the Formula1 parameter.
The following code will create a data validation drop-down list in cell A2:
Populate a Drop Down List From a Named Range in VBA
You can use a named range containing the items, to populate a drop-down list in VBA. We have the named range Animals shown below:
We have to set the Formula1 parameter equal to the named range. The following code will create a data validation drop-down list in cell A7 based on the items in the named range:
Removing the Drop Down List
You can use the Validation.Delete method to remove the drop-down list from the cell. The following code would remove the drop-down list from cell A7 in the example above:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Return to VBA Code Examples
VBA Drop Down List (Data Validation)
In this Article
- Creating a Drop Down List Using VBA
- Populate a Drop Down List From a Named Range in VBA
- Removing the Drop Down List
- VBA Coding Made Easy
This tutorial will demonstrate how to use Data Validation to work with drop-down lists in Excel using VBA.
Excel Data Validation allows you to limit what value(s) may be entered in a cell or range. You can limit entries to positive integers, text, dates, and much more. In this tutorial, we are going to look at how to create a Data Validation Drop-Down List in a cell using VBA.
Note: An alternative to a Data Validation Drop-Down list is a ListBox object. ListBoxes can be added to Excel worksheets. ListBoxes can trigger macros that run every time a ListBox value is changed. ListBoxes are also used in VBA Userforms.
Creating a Drop Down List Using VBA
We have the text Fruit in cell A1, and we are going to create a drop-down list in cell A2, with five entries.
We will use the Validation.Add method and specify that the Type parameter is xlValidateList. You can add the specific items you would like in your list using the Formula1 parameter.
The following code will create a data validation drop-down list in cell A2:
Sub DropDownListinVBA()
Range("A2").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="Orange,Apple,Mango,Pear,Peach"
End Sub
The result is:
Populate a Drop Down List From a Named Range in VBA
You can use a named range containing the items, to populate a drop-down list in VBA. We have the named range Animals shown below:
We have to set the Formula1 parameter equal to the named range. The following code will create a data validation drop-down list in cell A7 based on the items in the named range:
Sub PopulateFromANamedRange()
Range("A7").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="=Animals"
End Sub
The result is:
Removing the Drop Down List
You can use the Validation.Delete method to remove the drop-down list from the cell. The following code would remove the drop-down list from cell A7 in the example above:
Sub RemoveDropDownList()
Range("A7").Validation.Delete
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Ребят, а может мне кто-нибудь подскажет вариант реализации? Задача у меня такая: есть файл с адресами: Город, Улица, Дом — это столбцы. Файл для каждого региона свой, и он динамичный лежит в общем справочнике. Мы работаем с другим файлом, в который вставляется нужный листик, в зависимости от того, какой регион его открывает. Это я написала. Так вот… теперь надо, чтобы на другом листочке в столбцах Город/улица/дом, выходили выпадающие списки, причём для определённого города, только его улицы, а для улиц дома… При этом не должно быть пустых и улицы уникальны.
Я придумала два варианта реализации… Но они оба не отличаются особым успехом.
Первый: почти без VBA
с помощью VBA я создаю уникальный список городов и делаю его именем и прописываю кодом, что значение в столбце должно быть список с именем «Город»
далее, так как у меня есть список Город-Улица (на адресном листе), с помощью формулы смещения и поиска позиции нахожу улицы только этого города.(минус этого такой, что эта формула в именах постоянно почему-то (!) сбивается…)
Далее аналогично, этой же формулой нахожу дома для улиц.
Второй способ — не осуществила до конца, так как ступор… Создала уникальные города на отдельном листе в строку… Далее создала под каждым городом его улицы — так же уникальные… А вот теперь надо через ДВССЫЛ через VBA создать столько имён, сколько у меня вышло городов…. вообщем как это сделать…. если это реально…
Если есть другой вариант решения очень жду!!
Заранее спасибо