Table of Contents

Test a Selection

This program in Excel VBA uses the Count property IsNumeric function IsEmpty function and Intersect method to test a selection.

Situation:

Test a Selection in Excel VBA

Place a command button on your worksheet and add the following code lines:

1. First we declare two Range objects. We call the Range objects rng and cell.

Dim rng As Range cell As Range

2. We initialize the Range object rng with Range(“C4:D10”) and the Range object cell with the selected range.

Set rng = Range(“C4:D10”)
Set cell = Selection

3. Add the following code lines:

If cell.Count = 1 And IsNumeric(cell) And Not IsEmpty(cell) And Not Intersect(rng cell) Is Nothing Then
MsgBox “You win”
Else
MsgBox “You lose”
End If

Explanation: Intersect(rng cell) returns a Range object that represents the intersection of the two ranges. If this range object is not Nothing the single number (first three conditions) is in the bordered range.

4. Test the program.

Only when you select a single number in the bordered range the result will be:

Test a Selection Result

In all other cases the result will be:

Test a Selection Result

Leave A Comment

Excel meets AI – Boost your productivity like never before!

At Formulas HQ, we’ve harnessed the brilliance of AI to turbocharge your Spreadsheet mastery. Say goodbye to the days of grappling with complex formulas, VBA code, and scripts. We’re here to make your work smarter, not harder.

Related Articles

The Latest on Formulas HQ Blog