How do I check if a string is either a one digit number OR a two digit number and otherwise return false
?
Asked
Active
Viewed 1.8k times
4
-
2You can do this with VBA LIKE: Bool=Digits like "#" or Digits like "##" – Charles Williams Jan 27 '11 at 08:37
-
@charles can u put that in an answer please – JOE SKEET Jan 27 '11 at 16:23
-
Anyone having trouble with regular expressions, I found this tool to be very useful. http://gskinner.com/RegExr/ – MSpeed Mar 29 '11 at 09:43
-
Here is another helpful [link](http://stackoverflow.com/q/22542834/2521) to Regex specific to Excel, with examples. – Automate This Mar 25 '14 at 03:50
5 Answers
10
How about:
Function OneOrTwo(i As Integer) As Boolean
Dim objRegEx As Object
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.Pattern = "^\d{1,2}$"
OneOrTwo = objRegEx.Test(i)
End Function

Fionnuala
- 90,370
- 7
- 114
- 152
-
1+1 although the `IgnoreCase` and `Global` lines are redundant for checking a numeric string. – brettdj Dec 29 '13 at 10:26
8
You can also do this using VBA LIKE:
Function OneOrTwo(Digits As Variant) As Boolean
OneOrTwo = Digits Like "#" Or Digits Like "##"
End Function

Charles Williams
- 23,121
- 5
- 38
- 38
1
IF CInt(myNumberString) < 100 Then
MsgBox "String must be either 1 or 2 digits"
Else
Msgbox "Failed"
End IF
Should work for you.

Damon Skelhorn
- 1,491
- 11
- 18
1
Remou had it right. Here is a RegexContains function so you can use it with all sorts of patterns, not just the one you need now.
Function RegexContains(ByVal find_in As String, _
ByVal find_what As String, _
Optional IgnoreCase As Boolean = False) As Boolean
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = find_what
RE.IgnoreCase = IgnoreCase
RE.Global = True
RegexContains = RE.Test(find_in)
End Function
Following the example from Remou, assuming the cell is A1, you'd write:
=RegexContains(A1, "^\d{1,2}$")

Gaijinhunter
- 14,587
- 4
- 51
- 57
0
Here is what I would try. /d for digit, ? for option 2 digits.
/d/d?
or
/d{1,2}

Lee Louviere
- 5,162
- 30
- 54