Intercept only number in string

User avatar
sal21
PlatinumLounger
Posts: 4364
Joined: 26 Apr 2010, 17:36

Intercept only number in string

Post by sal21 »

Trovati : 9 - Records

i have this string in a var MyString

I need to extract only the number from ":" and "-" in this case is 9

But the length of number is dinamic, i can have:

Trovati : 249 - Records
Trovati : 149 - Records
Trovati : 145879 - Records

How to?
Tks.

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Intercept only number in string

Post by HansV »

Try this:

Code: Select all

Dim p1 As Long
Dim p2 As Long
Dim lngNumber As Long
p1 = InStr(MyString, ":")
p2 = InStr(p1 + 1, MyString, "-")
lngNumber = Val(Trim(Mid(MyString, p1 + 1, p2 - p1 - 1)))
Best wishes,
Hans

User avatar
Jan Karel Pieterse
Microsoft MVP
Posts: 656
Joined: 24 Jan 2010, 17:51
Status: Microsoft MVP
Location: Weert, The Netherlands

Re: Intercept only number in string

Post by Jan Karel Pieterse »

Like this:

Code: Select all

Sub test()
    Dim sTest As String
    sTest = "Trovati : 249 - Records"
    MsgBox Trim(Split(Split(sTest, ":")(1), "-")(0))
End Sub
Explanation:
The inner trim part:
Split(sTest, ":")(1)
gives an array of two strings:
"Trovati :"
and
" 149 - Records"

The (1) then takes the second string
" 149 - Records"
and the outer split function splits it into:
" 149 "
and
" Records"
The (0) takes the first string " 149 " and the trim function removes the leading and trailing spaces.
Regards,

Jan Karel Pieterse
Excel MVP jkp-ads.com

User avatar
sal21
PlatinumLounger
Posts: 4364
Joined: 26 Apr 2010, 17:36

Re: Intercept only number in string

Post by sal21 »

Jan Karel Pieterse wrote:Like this:

Code: Select all

Sub test()
    Dim sTest As String
    sTest = "Trovati : 249 - Records"
    MsgBox Trim(Split(Split(sTest, ":")(1), "-")(0))
End Sub
Explanation:
The inner trim part:
Split(sTest, ":")(1)
gives an array of two strings:
"Trovati :"
and
" 149 - Records"

The (1) then takes the second string
" 149 - Records"
and the outer split function splits it into:
" 149 "
and
" Records"
The (0) takes the first string " 149 " and the trim function removes the leading and trailing spaces.
Tks! the code work well... and tks for Explanation.

User avatar
sal21
PlatinumLounger
Posts: 4364
Joined: 26 Apr 2010, 17:36

Re: Intercept only number in string

Post by sal21 »

HansV wrote:Try this:

Code: Select all

Dim p1 As Long
Dim p2 As Long
Dim lngNumber As Long
p1 = InStr(MyString, ":")
p2 = InStr(p1 + 1, MyString, "-")
lngNumber = Val(Trim(Mid(MyString, p1 + 1, p2 - p1 - 1)))
Wow! nice code. tks