4

How do I check if a string is either a one digit number OR a two digit number and otherwise return false?

JimmyPena
  • 8,630
  • 6
  • 42
  • 64
JOE SKEET
  • 7,786
  • 13
  • 46
  • 64

5 Answers5

9

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

See: http://msdn.microsoft.com/en-us/library/ms974570.aspx

Fionnuala
  • 89,471
  • 7
  • 106
  • 145
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
  • 22,530
  • 5
  • 35
  • 37
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,451
  • 11
  • 17
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}$")

aevanko
  • 14,283
  • 4
  • 50
  • 57
0

Here is what I would try. /d for digit, ? for option 2 digits.

/d/d?

or

/d{1,2}

Lee Louviere
  • 5,104
  • 29
  • 54