Access VBA: Extract number after a specific word from a full length string



If we need to extract a number after a specific word from a full length string, as shown in below example, we can use below function


Private Sub Command1_Click() 
Dim db As DAO.Database
Set db = CurrentDb
Dim x As String
Dim y As String
x = "SpecificWord_1234 56"
y = GetNumber(Mid(x, InStr(x, "SpecificWord_") + 13))
'MsgBox GetNumber(x) 
MsgBox y 
End Sub

' Note 'SpecificWord_' has 13 chars.'Hence mentioned 13.'It as to be length of the SpecificWord that you are specifying

-----------------------------------------------------------------------------------------------

Function GetNumber(varS As Variant) As Variant 


Dim x As Integer
GetNumber = Null 


If varS & "" Like "*#*" Then
For x = 1 To Len(varS)
If IsNumeric(Mid(varS, x, 1)) Then
GetNumber = Val(Mid(Replace(varS, " ", "|"), x))

' GetNumber = Replace(varS, " ", "|") -- commented - for step by step test if needed
' GetNumber = Mid(GetNumber, x) -- commented - for step by step test if needed
' GetNumber = Val(GetNumber) -- commented - for step by step test if needed

Exit For

End If
Next

End If
End Function

Example: If we need to extract first occurrence number available after the word DoorNumber, from below full string
SomeWord_123_SomeOtherWords_DoorNumber_12345_OtherWord_456

In this case we have to modify the function as shown below

y = GetNumber(Mid(x, InStr(x, "DoorNumber_") + 11)) 'Because length of (DoorNumber_) is 11

No comments:

Post a Comment