PDA

View Full Version : Parse text to array



amir0914
04-11-2020, 01:37 PM
Hi everyone,
I want to parse all numbers of text and add them to array, for example ,the text is : "Amir 123yildiz969ankara 53 ali25" ,I want to make an array with separate numbers :
array = (123,969,53,25)

Is it possible to do that with vba?
Thanks in advanced.

paulked
04-11-2020, 03:35 PM
This:


Sub GetNum()
Dim x As Long, y As Long, st As String, str As String, ar As Variant
st = "Amir 123yildiz969ankara 53 ali25"
For x = 1 To Len(st)
If IsNumeric(Mid(st, x, 1)) Then
str = str & Mid(st, x, 1)
y = 0
Else
If x <> 1 And y = 0 Then str = str & ","
y = 1
End If
Next
If Right(str, 1) = "," Then str = Left(str, Len(str) - 1)
ar = Split(str, ",")
End Sub


will give ar as the array, or as a function:




Function NumArr(st As String) As Variant
Dim x As Long, y As Long, str As String
For x = 1 To Len(st)
If IsNumeric(Mid(st, x, 1)) Then
str = str & Mid(st, x, 1)
y = 0
Else
If x <> 1 And y = 0 Then str = str & ","
y = 1
End If
Next
If Right(str, 1) = "," Then str = Left(str, Len(str) - 1)
NumArr = Split(str, ",")
End Function

Paul_Hossler
04-11-2020, 06:18 PM
Option Explicit


Sub test()
Dim s As String, s1 As String
Dim i As Long
Dim ary As Variant

s = "Amir 123yildiz969ankara 53 ali25"

For i = 1 To Len(s)
Select Case Mid(s, i, 1)
Case "0" To "9"
s1 = s1 & Mid(s, i, 1)
Case Else
s1 = s1 & ","
End Select
Next i

Do While InStr(s1, ",,") > 0
s1 = Replace(s1, ",,", ",")
Loop

If Left(s1, 1) = "," Then s1 = Right(s1, Len(s1) - 1)
If Right(s1, 1) = "," Then s1 = Left(s1, Len(s1) - 1)

ary = Split(s1, ",")

Stop

End Sub

snb
04-12-2020, 02:16 AM
Sub M_snb()
c00 = "Amir 123yildiz969ankara 53 ali25"

For j = 1 To Len(c00)
If Asc(Mid(c00, j, 1)) > 57 Then c00 = Replace(c00, Mid(c00, j, 1), " ")
Next
sn = Split(Application.Trim(c00))

MsgBox Join(sn, vbLf)
End Sub

or


Sub M_snb_000()
c00 = "Amir 123yildiz969ankara 53 ali25"

With CreateObject("VBScript.RegExp")
.Pattern = "\D+"
.Global = True
sn = Split(Trim(.Replace(c00, " ")))
End With

MsgBox Join(sn, vbLf)
End Sub

amir0914
04-12-2020, 02:06 PM
Thanks to all for replying. they were very useful, can you give a code to split all text string and numbers in array? like this :
array = ("Amir",123,"yildiz",969,"ankara","53","Ali","25")

snb
04-12-2020, 02:20 PM
Were you able to solve the assignment ?

paulked
04-12-2020, 02:35 PM
Were you able to solve the assignment ?

Ha! 1st lesson completed!


can you give a code to split all text string and numbers in array? like this :
array = ("Amir",123,"yildiz",969,"ankara","53","Ali","25")

Easy to adapt the above code to do just that :yes

snb
04-13-2020, 12:52 AM
The quality of your solution deserves an A.