Extracting numbers from a string

Will the data always be space character delimited?

If so, could implement a "scan for space character / consider that word between two space characters if it is numeric" rather than going a character at a time.

Please confirm my question, sample air code to follow only if you choose "yes".

Ahh...I see what you mean. Yes.
 
Ahh...I see what you mean. Yes.

Very well, consider this quick sample code...

Code:
Private Sub btnTestParseString_Click()
On Error GoTo Err_btnTestParseString_Click

  Dim strIn As String
  Dim lMaxStep As Long
  Dim lStep As Long
  Dim strThisChar As String
  Dim strFindChar As String
  Dim lFstFoundChar As Long
  Dim strThisWord As String

  strIn = "1 Day I went to see 5 elephants at the zoo. It was 2.5 miles away from my 4 bedroom house"
  lMaxStep = Len(strIn)

  strFindChar = Chr(32)
  lFstFoundChar = 1

  If lMaxStep > 0 Then
    For lStep = 1 To lMaxStep
      strThisChar = Mid(strIn, lStep, 1)
      If strThisChar = strFindChar Then
        strThisWord = Mid(strIn, lFstFoundChar, lStep - lFstFoundChar)
        Debug.Print ">" & strThisWord & "<"
        If IsNumeric(strThisWord) = True Then
          Debug.Print "Is numeric, so do something..."
        End If
        lFstFoundChar = lStep + 1
      End If
    Next lStep
  End If

Exit_btnTestParseString_Click:
  Exit Sub

Err_btnTestParseString_Click:
  Call errorhandler_MsgBox("Form: Form_TestCollection, Subroutine: btnTestParseString_Click()")
  Resume Exit_btnTestParseString_Click

End Sub
Immediate window output...

Code:
>1<
Is numeric, so do something...
>Day<
>I<
>went<
>to<
>see<
>5<
Is numeric, so do something...
>elephants<
>at<
>the<
>zoo.<
>It<
>was<
>2.5<
Is numeric, so do something...
>miles<
>away<
>from<
>my<
>4<
Is numeric, so do something...
>bedroom<
 
Quick example:
Code:
Function ExtractNumbers(inputVal As String)
    Dim outputArray()   As Variant
    Dim prevIsNumeric   As Boolean
    Dim midChar         As Variant
    Dim upperBound      As Long
    Dim pos             As Long
    
    upperBound = Len(inputVal)
    ReDim outputArray(1 To upperBound)
    
    For x = 1 To upperBound
        midChar = Mid(inputVal, x, 1)
        
        If IsNumeric(midChar) Or midChar = "." Then
            If prevIsNumeric Then
                outputArray(pos) = outputArray(pos) & midChar
            Else
                pos = pos + 1
                outputArray(pos) = midChar
            End If
            prevIsNumeric = True
        Else
            prevIsNumeric = False
        End If
    Next
     
    ReDim Preserve outputArray(1 To pos)
End Function
If you don't want to "catch" doubles (i.e. decimal numbers) then remove the midChar = "." part.
 

Users who are viewing this thread

Back
Top Bottom