Forum Discussion
Ps18priyanka
Sep 26, 2021Copper Contributor
Excel problem: I need to let only values between a certain range be in a column and if they are less
I need to let only values between a certain range be in a column and if they are lesser or higher than the specified range, I want it to show the particular minimum or maximum number corresponding to ...
HansVogelaar
Sep 26, 2021MVP
You could use Data Validation to allow only values between a specified minimum and maximum:
If you want to allow the user to enter values outside the range but to convert them automatically to the minimum/maximum, that would require VBA:
- Right-click the sheet tab.
- Select View Code from the context menu.
- Copy the code listed below into the worksheet's code module.
- Switch back to Excel.
- Save the workbook as a macro-enabled workbook (*.xlsm).
- Make sure that you allow macros when you open the workbook.
Private Sub Worksheet_Change(ByVal Target As Range)
' Change these as required
Const TheMin = 20
Const TheMax = 40
Dim rng As Range
Dim cel As Range
' Change the range below to the range you want to restrict
Set rng = Range("D2:D1000")
If Not Intersect(rng, Target) Is Nothing Then
Application.ScreenUpdating = False
Application.EnableEvents = False
For Each cel In Intersect(rng, Target)
If cel.Value <> "" Then
If cel.Value < TheMin Then
cel.Value = TheMin
ElseIf cel.Value > TheMax Then
cel.Value = TheMax
End If
End If
Next cel
Application.EnableEvents = True
Application.ScreenUpdating = True
End If
End Sub