Excel VBA: Validate text is range

ouestque
ouestque used Ask the Experts™
on
What VBA would I need to validate a string can also be a range?

Example:
Assume I have a sheet where the user enters text in A1. If the text can be a range like "B20" then show a message box that says, "This is a range!!"

"A1" = True: It is a range
"2-2A" = False: is not a range
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You'll probably need to capture an error using the EVALUATE method. Something like this...

Function ValidateRange(str As String) As Boolean
    Dim x As String
    On Error Resume Next
    x = Evaluate(str)
    ValidateRange = (Err.Number = 0)
    On Error GoTo 0
End Function

Open in new window

Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015
Commented:
You may declare a range variable and set it with the text entered in A1 and if the text entered is a valid address of a cell/range, the range variable will be set without an error else it will not be set and will be nothing and then you can test if the range variable is set correctly or not to prompt the user.
e.g. place the following change event code on Sheet Module and test it by entering a test string in cell A1.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
Dim rng As Range
If Target.Address(0, 0) = "A1" Then
    Target.Select
    On Error Resume Next
    Set rng = Range(Target)
    On Error GoTo 0
    If Not rng Is Nothing Then
        MsgBox Target & " is a range."
    Else
        MsgBox Target & " is not a range."
    End If
End If
End Sub

Open in new window

Subodh Tiwari (Neeraj)Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015

Commented:
Both the answers resolved the original question.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial