Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add data validation to a cell with VBA
#1
Example:

Sub AddDataValidation()
    With Range("A1").Validation
        .Delete 'Clear any existing validation
        .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=1, Formula2:=100
        .ErrorMessage = "Enter a whole number between 1 and 100."
        .IgnoreBlank = True
        .InCellDropdown = True
    End With
End Sub

Explanation:

The code defines a subroutine named AddDataValidation.
The With statement is used to work with the data validation settings for cell A1.
The existing validation (if any) is cleared using the Delete method.
The Add method is used to add new data validation settings to the cell.
Type:=xlValidateWholeNumber specifies that only whole numbers are allowed.
AlertStyle:=xlValidAlertStop sets the alert style to stop, which displays an error message when an invalid value is entered.
Operator:=xlBetween indicates that the data should be between two values.
Formula1:=1 and Formula2:=100 set the lower and upper bounds for the data validation.
The ErrorMessage property is used to set the error message that appears when an invalid value is entered.
IgnoreBlank = True allows blank cells without triggering an error.
InCellDropdown = True enables the drop-down arrow in the cell for easy data selection.
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copy data to another worksheet Qomplainerz 0 399 07-27-2023, 11:24 AM
Last Post: Qomplainerz
  Concatenate data in columns Qomplainerz 0 346 07-27-2023, 11:01 AM
Last Post: Qomplainerz
  Create a pivot table based on data in a worksheet with VBA Qomplainerz 0 415 07-27-2023, 09:48 AM
Last Post: Qomplainerz
  Filter data in a worksheet Qomplainerz 0 382 07-27-2023, 09:46 AM
Last Post: Qomplainerz
  Create a chart from data with VBA Qomplainerz 0 381 07-27-2023, 09:44 AM
Last Post: Qomplainerz
  Sort data in a range with VBA Qomplainerz 0 367 07-27-2023, 09:43 AM
Last Post: Qomplainerz
  Insert a new row and fill it with data in VBA Qomplainerz 0 343 07-27-2023, 09:11 AM
Last Post: Qomplainerz
  Change cell colors based on values with VBA Qomplainerz 0 320 07-27-2023, 08:19 AM
Last Post: Qomplainerz
  Copy data from one workbook to another with VBA Qomplainerz 0 330 07-27-2023, 08:02 AM
Last Post: Qomplainerz
  Running VBA code when a cell's value changes Qomplainerz 0 263 07-27-2023, 07:04 AM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 7 Guest(s)