Home » excel » How do I constrain a value to a range in excel?

How do I constrain a value to a range in excel?

Posted by: admin March 7, 2020 Leave a comment

Questions:

In C++ I would use boost::clamp for this. Basically I have some excel function

A1*B2+C3+D4

I want to do constrain it to +/- some number, call it X1. The obvious way is this:

MAX(-X1, MIN(X1, A1*B2+C3+D4))

But I want to be able to do this:

CLAMP(A1*B2+C3+D4, -X1, X1)

Does this or something similar exist? I’m just curious – obviously the workaround works, it’s just ugly.

How to&Answers:

With spreadsheet formulas I don’t think that you can do much better than that min/max construct. You could write clamp in VBA:

Function clamp(x As Double, lower As Double, upper As Double) As Double
    If x < lower Then
        clamp = lower
    ElseIf x > upper Then
        clamp = upper
    Else
        clamp = x
    End If
End Function

If you enter that in a standard code module then you could e.g. do something like this:

enter image description here

In column A I have values in the range 0 to 2*pi. In C2 I have the value 0.5. In B1 I entered

=clamp(SIN(A1),-$C$2,$C$2)

and copied down. The graph shows the result.

(Since I gave a VBA solution I’ll add the Excel-VBA tag. Even if you prefer a non-VBA solution, it is possible that others in the future might search the question and be comfortable with a VBA solution).

Answer:

This can be done using MEDIAN. MEDIAN picks the middle of the three values, thus effectively restricting the lower and upper limits.

For example say your minimum is 5 and your maximum is 10:

=MEDIAN(5,0,10) is 5

=MEDIAN(5,7,10) is 7

=MEDIAN(5,12,10) is 10