Question : Searching for number range in string

User will input the following type of string:
sleep8pmwake7am

I want to use instr() to verify the formatting.
The below code is obvioulsy blowing up.
How can I serach for a range of numerics?

If InStr(1, strString, "sleep" & %[0-9]% & "pm", vbTextCompare)  = 1 or _
If InStr(1, strString, "sleep" & %[0-9]% & " & %[0-9]% & "pm", vbTextCompare) = 1 then
Do stuff
End if

Answer : Searching for number range in string

Hi GWitek

You could do this using regular expressions, but I think it's too complex for a simple Like test.

However, I assume the objective is not just to validate the string, but also to extract the two times from it.  Therefore, I suggest you use a function (attached) to parse the string and return the sleep and wake times.

Use it like this:

Dim tSleep as Date, tWake as Date
If ParseSleepWake( strString, tSleep, tWake ) Then
   MsgBox "sleep at " & tSleep & ", wake at " & tWake
Else
   MsgBox "invalid string"
End If

The function is thoroughly commented, so I hope you can follow how it works :-)

--
Graham

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
Public Function ParseSleepWake(sInput As String, tSleep As Date, tWake As Date) As Boolean
Dim sTemp As String, sSleepAmPm As String, sWakeAmPm As String
Dim iSleep As Integer, iWake As Integer
' assume invalid
ParseSleepWake = False
' remove any leading or trailing spaces
sTemp = Trim(sInput)
' process the sleep part
If Left(sTemp, 5) <> "sleep" Then Exit Function
' remove "sleep" and any following spaces
sTemp = LTrim(Mid(sTemp, 6))
' see if the next is a valid number
iSleep = Val(sTemp)
If iSleep < 1 Or iSleep > 12 Then Exit Function
' remove number and any following spaces
sTemp = LTrim(Mid(sTemp, IIf(iSleep > 9, 3, 2)))
' get am/pm
sSleepAmPm = Left(sTemp, 2)
If sSleepAmPm <> "am" And sSleepAmPm <> "pm" Then Exit Function
' remove am/pm and any following spaces
sTemp = LTrim(Mid(sTemp, 3))
' process the wake part
If Left(sTemp, 4) <> "wake" Then Exit Function
' remove "sleep" and any following spaces
sTemp = LTrim(Mid(sTemp, 5))
' see if the next is a valid number
iWake = Val(sTemp)
If iWake < 1 Or iWake > 12 Then Exit Function
' remove number and any following spaces
sTemp = LTrim(Mid(sTemp, IIf(iWake > 9, 3, 2)))
' we should have only am/pm left
sWakeAmPm = sTemp
If sWakeAmPm <> "am" And sWakeAmPm <> "pm" Then Exit Function
' everything is now OK
tSleep = CDate(iSleep & sSleepAmPm)
tWake = CDate(iWake & sWakeAmPm)
ParseSleepWake = True
End Function
Random Solutions  
 
programming4us programming4us