Добрый день, знатоки Excel!
Необходимо написать макрос, который бы формировал выпадающий список полей «умной таблицы».
Пишу вручную, записываю мастером макросов:
Код |
---|
With Selection.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=ДВССЫЛ(""Таблица1[#Заголовки]"")" End With |
Потом запускаю — выдает ошибку 1004. Пробовал по-английски так:
Код |
---|
With Selection.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=INDIRECT(""Таблица1[#Заголовки]"")" End With |
Опять ошибка. Пробовал так:
Код |
---|
With Selection.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=INDIRECT(""Таблица1[#Headers]"")" End With |
Что интересно, ошибки нет, но вставляется в проверку данных такая лабуда: =ДВССЫЛ(«Таблица1[#Headers]») и, конечно, не работает.
Сломал всю голову уже, помогите, что не так делаю?
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
In this article I will explain how you can create drop down lists using data validation.
Jump To:
- Creating Data Validation (Manually)
- Creating Data Validation (Using VBA)
- Selection Change
- Modifying, Adding, Inserting and Removing Items (Usin VBA)
You can download the file and code related to this article from the link below:
- Drop Down Lists Data Validation.xlsm
–
Creating Data Validation (Manually):
Step1 : In the first step you would need to print the data you are going to fill the drop down list with somewhere. Usually I open a new sheet, name it something no one would ever consider using (like “far43fq”) and print the data there.
Step 2: Select the cell you would like to add the drop down list to. Then click on the Data Validation button on the Data Ribbon:
Step 3: Select list:
Step 4: Input the range of the data. If the drop down list (data validation) and the data are in the same sheet you would reference them using a statement like “=A1:A6”. If they are in separate sheets you would use a statement like “=SheetName!A1:A6”, where “SheetName” is replaced with the name of the sheet.
Note: I this example the input data is in another sheet. The name of the sheet is Sheet1″.
After pressing Ok your drop down list is ready:
–
Creating Data Validation (Using VBA):
Using the code below a drop down list (data validation) will be created in the cell “J2” . The data for the drop down list will come from the range “=A1:A6” in the sheet “Sheet1”. Note you must change the highlighted parts based on the location of your source and the location for your drop down list:
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:= xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
–
Selection Change:
The data validation itself doesn’t have a built in function for determining when the user has selected a new value. Though you could use the worksheet_change event handler to determine when the user has selected a new value from the drop down list. The worksheet_change event triggers every time changes are made to a worksheet. You could use the worksheet_change event handler to catch this event and check if the changes made were to the value selected in the drop down list.
The code below is a worksheet_change event handler. It checks if the changes in the worksheet have occurred in the cell with the drop down list or not:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Range("J2").Address Then
'your code
End If
End Sub
–
Modifying, Adding, Inserting and Removing Items (Usin VBA):
In order to modify, add, insert and remove items from a drop down list created using data validation, you would have to follow 2 steps.
Step 1: The first thing you would have to do is change the source data. For example lets say we want to modify the second item to “New Item 2”, we would need to change the data validation’s source to the values below:
Or for example lets say we want to add an item to the list of items. Again the first thing would be to modify the source data:
Or for example lets say we want to remove “item 4”. Again the first step would be to modify the source data:
Step 2: In the next step we need to update the drop down list to accommodate for the changes made in its source. This can be done using the code below. The code below must be copied to the sheet with the source data. The highlighted parts must be changed based on the location of your source data and the location you would like the drop down list to appear:
Option Explicit
Dim flagProgram As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
Dim intRowCount As Integer
If flagProgram = False Then
flagProgram = True
'get the total rows of data
intRowCount = Get_Count
'update the drop down list(data validation)
Call Update_DataValidation(intRowCount)
flagProgram = False
End If
End Sub
'This function will return the total count of rows in the
'drop down list(data validation) source
Private Function Get_Count() As Integer
'counter
Dim i As Integer
'determines if the we have reached the end
Dim flag As Boolean
i = 1
flag = True
While flag = True
If Cells(i, 1) <> "" Then
'if there is still data go on
i = i + 1
Else
'if there is no more data left stop the loop
flag = False
End If
Wend
'return the total row count
Get_Count = i - 1
End Function
'the function below updates the source range for the data validation
'based on the number of rows provided by the input
Private Sub Update_DataValidation(ByVal intRow As Integer)
'the reference string to the source range
Dim strSourceRange As String
strSourceRange = "=Sheet1!A1:A" + Strings.Trim(Str(intRow))
With Sheet2.Range("J2").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:= xlBetween, Formula1:=strSourceRange
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
The code above has 3 different function. The main function is Worksheet_Change event handler. The event handler executes when the user makes changes to the sheet with the source data:
Private Sub Worksheet_Change(ByVal Target As Range)
...
End Sub
flagProgram determines if the current changes made to the sheet have been done by the program or the user. This is to prevent an endless recursion of the Worksheet_Change event handler:
If flagProgram = False Then
flagProgram = True
...
flagProgram = False
End If
The line below gets the number of rows in the source for the data validation. This value must be checked each time to account for added and removed items:
intRowCount = Get_Count
The function Update_DataValidation updates the data validation based on the input parameter intRow. The input parameter intRow determines how many rows of data the drop down list must use. The first line of this function creates a string which is a reference to the range with the source data:
strSourceRange = "=Sheet1!A1:A" + Strings.Trim(Str(intRow))
Note the highlighted section must changed if your source data is not in Sheet1 starting from cell A1. The resulting string will be something like this:
“=Sheet1!A1:A5”
or
“=Sheet1!A1:A7”
For more information about string processing and manipulation please see the link below:
- VBA Excel, String Processing and Manipulation
The rest of the lines in the function Update_DataValidation creates a drop down list in the cell “J2” in sheet2.
You can download the file and code related to this article from the link below:
- Drop Down Lists Data Validation.xlsm
See also:
- VBA Excel, String Processing and Manipulation
- Excel Drop Down Lists
- VBA UserForm Drop Down Lists
If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website www.software-solutions-online.com
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
Add data validation input messages to cells in Excel with this free Excel macro. These messages appear when a specific cell has been selected. The benefit of this type of pop up message in Excel is that when a user goes to enter something in a particular cell, you can display a reminder to that user which can better help them fill out that cell. This works great when it comes to user forms and data entry forms in Excel.
There are two versions of this macro listed below. The first Excel macro adds an input message to a cell that is hard-coded into the macro whereas the second macro adds an input message to any cell that you select before you run the macro.
To use these macros simply change A1 in the first macro to the cell reference where you want to add an input message and change Message Title Goes Here and Message Contents Go Here in both macros in order to have the desired input message displayed.
Where to install the macro: Module
Add an Input Message to a Specified Cell in Excel
Sub Add_Cell_Input_Message_Cell()
With Range("A1").Validation
.Add Type:=xlValidateInputOnly
.InputTitle = "Message Title Goes Here"
.InputMessage = "Message Contents Go Here"
End With
End Sub
Add an Input Message to a Selected Cell in Excel
Sub Add_Cell_Input_Message_Selection()
With Selection.Validation
.Add Type:=xlValidateInputOnly
.InputTitle = "Message Title Goes Here"
.InputMessage = "Message Contents Go Here"
End With
End Sub
Excel VBA Course — From Beginner to Expert
200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides
Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)
View Course
How to Install the Macro
- Select and copy the text from within the grey box above.
- Open the Microsoft Excel file in which you would like the Macro to function.
- Press «Alt + F11» — This will open the Visual Basic Editor — Works for all Excel Versions.
Or For other ways to get there, Click Here. - On the new window that opens up, go to the left side where the vertical pane is located. Locate your Excel file; it will be called VBAProject (YOUR FILE’S NAME HERE) and click this.
- If the Macro goes in a Module, Click Here, otherwise continue to Step 8.
- If the Macro goes in the Workbook or ThisWorkbook, Click Here, otherwise continue to Step 8.
- If the Macro goes in the Worksheet Code, Click Here, otherwise continue to Step 8.
- Close the Microsoft Visual Basic Editor window and save the Excel file. When you close the Visual Basic Editor window, the regular Excel window will not close.
- You are now ready to run the macro.
Excel VBA Course — From Beginner to Expert
200+ Video Lessons
50+ Hours of Video
200+ Excel Guides
Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)
View Course