-
split a variable
how do i split a variable into alphabetic & numeric strings for example
dim string1 as string
dim string 2 as string
dim int1 as integer
string1 = "abcd1234"
must be split into two variables where alphabetic part goes to the variable of type string say
string2 = abcd
& numeric part goes to a variable of type integer say
int1 = 1234
thanks in advance.
-
Welcome to the forum!
Various Regular Expressions methods would be one route. If your data is always strings and then a number, other methods can be used. Is this the case?
Would a worksheet formula method rather than a vba method be preferred?
-
yes my data is always strings & then a number, no a worksheet formula would not work cause the data is in a array & it is array size is quite large.
-
[VBA]
Sub SplitIt()
Dim i$, Num$, txt$
i = "abc0123"
Num = StrReverse(Val(StrReverse(i)))
txt = Left(i, Len(i) - Len(Num))
MsgBox Num & " - " & txt
End Sub
[/VBA]
MVP (Excel 2008-2010)
Post a workbook with sample data and layout if you want a quicker solution.
To help indent your macros try Smart Indent
Please remember to mark threads 'Solved'
-
@MD Thank you,
The solution you have provided seems to be working for now.
Yes the array size is in the order of 5 digits.
-
Not so good with
i = "abc01230"
MVP (Excel 2008-2010)
Post a workbook with sample data and layout if you want a quicker solution.
To help indent your macros try Smart Indent
Please remember to mark threads 'Solved'
-
[VBA]Sub SplitIt()
Dim i#, Num$, txt$, test$
test = "abc01230"
i = 1
Do Until IsNumeric(Mid(test, i, 1))
i = i + 1
Loop
txt = Left(test, i - 1)
Num = Replace(test, txt, "")
MsgBox txt & " - " & Num
End Sub[/VBA]
MVP (Excel 2008-2010)
Post a workbook with sample data and layout if you want a quicker solution.
To help indent your macros try Smart Indent
Please remember to mark threads 'Solved'
-
A tweak of mdmackillop's previous routine avoids looping.
[VBA]Sub SplitIt2()
Dim i$, Num$, txt$
i = "abc01230"
Num = Mid(i, InStr(i, StrReverse(Val(StrReverse(i)))))
txt = Left(i, Len(i) - Len(Num))
MsgBox Num & " - " & txt
End Sub[/VBA]
-
Hi Mike
Thanks for the improvement.
MVP (Excel 2008-2010)
Post a workbook with sample data and layout if you want a quicker solution.
To help indent your macros try Smart Indent
Please remember to mark threads 'Solved'
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules