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.
Intercept only number in string
-
- Administrator
- Posts: 78549
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: Intercept only number in string
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
Hans
-
- Microsoft MVP
- Posts: 656
- Joined: 24 Jan 2010, 17:51
- Status: Microsoft MVP
- Location: Weert, The Netherlands
Re: Intercept only number in string
Like this:
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.
Code: Select all
Sub test()
Dim sTest As String
sTest = "Trovati : 249 - Records"
MsgBox Trim(Split(Split(sTest, ":")(1), "-")(0))
End Sub
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.
-
- PlatinumLounger
- Posts: 4364
- Joined: 26 Apr 2010, 17:36
Re: Intercept only number in string
Tks! the code work well... and tks for Explanation.Jan Karel Pieterse wrote:Like this:Explanation:Code: Select all
Sub test() Dim sTest As String sTest = "Trovati : 249 - Records" MsgBox Trim(Split(Split(sTest, ":")(1), "-")(0)) End Sub
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.
-
- PlatinumLounger
- Posts: 4364
- Joined: 26 Apr 2010, 17:36
Re: Intercept only number in string
Wow! nice code. tksHansV 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)))