|
|
|
|
|
|
Multiple Apps
|
Test if ?X? is between two values, X1 and X2
|
|
Ease of Use
|
Intermediate
|
Version tested with
|
2000
|
Submitted by:
|
MWE
|
Description:
|
IsBetween is a boolean function that tests if X is between X1 and X2. The actual test is if X is between Min(X1,X2) and Max (X1,X2)
|
Discussion:
|
Checking if a value, X, is between a pair of numbers, say X1 and X2 is a common need in VBA applications. The Boolean function IsBetween performs this task. Although it seems reasonable that X1 < X2, IsBetween does not really care and really tests if X is between Min ( X1 , X2 ) and Max (X1 , X2 ). IsBetween has the ability to check for the two basic cases: if Xmin <= X <= Xmax or if Xmin < X < Xmax. The first case is often called ?inclusive? because the end points are included in the test. The second case is often called ?exclusive? because the end points are excluded from the test. Note that for an exclusive test, if X = X1 or X = X2, IsBetween would return ?False?. The argument IncExc tells IsBetween which test to perform. IncExc is optional; the default is ?inc?, i.e., the end points are included in the test.
IsBetween can be used in any VBA application. The demo is Excel-based.
|
Code:
|
instructions for use
|
Option Explicit
Function IsBetween( _
X, _
X1, _
X2, _
Optional IncExc = "inc") As Boolean
Dim Xmax
Dim Xmin
If X1 <= X2 Then
Xmin = X1
Xmax = X2
Else
Xmin = X2
Xmax = X1
End If
Select Case LCase(IncExc)
Case "inc"
If X >= Xmin And X <= Xmax Then
IsBetween = True
Else
IsBetween = False
End If
Case "exc"
If X > Xmin And X < Xmax Then
IsBetween = True
Else
IsBetween = False
End If
Case Else
MsgBox "bad call to IsBetween"
End Select
End Function
|
How to use:
|
- Copy the above code.
- Open any workbook.
- Press Alt + F11 to open the Visual Basic Editor (VBE).
- In the left side window, hi-lite the target spreadsheet [it will likely be called VBAProject(filename.xls) where filename is the name of the spreadsheet]
- Select an existing code module for the target worksheet; or from the Insert Menu, choose Insert | Module.
- Paste the code into the right-hand code window.
- Close the VBE, save the file if desired.
- See ?Test The Code? below
|
Test the code:
|
- Open the example
- The example/demo spreadsheet contains a single sheet, the IsBetween procedure and a demo procedure to read values from the spreadsheet and call IsBetween.
- Enter values for X, X1, X2 and IncExc in the appropriate cells
- Click on the command button
- The demo should return an appropriate answer.
- NOTE: the worksheet is protected so that only the green cells may be changed. The IncExc input cell is also controlled via Excel?s validation protocol to encourage the entry of either ?inc? or ?exc?
|
Sample File:
|
IsBetween.zip 17.78KB
|
Approved by mdmackillop
|
This entry has been viewed 94 times.
|
|