Splitting specific length numbers in excel with conditions in excel

Viewed 29

0002786961 TRAK CDFA #: 0008787942 2722 2723 4536841 N/A 2786952 4345784 001018809~00077480

Above is an example of data line I need to split these into 3 types:

  • First column: starts with 2 and is of 4 digit (2722 in above example)
  • Second: starts with 2 and is of 7 digit(2786952 in above example)
  • Third: starts with 4 is of 7 digit (4345784 4536841 in above example)

I tried separating everything into different columns and then putting IF AND conditions that I mentioned above but the problem is not everything is getting separated and splitting everything is not efficient enough.

I am not able to figure out a vba code for something that satisfies all the conditions and works too.

Can anyone help me out?

Code tried:

IF(AND(LEFT(A4,1) = "2",LEN(A4) < 5), A4, "No")

This doesn't separate 4 digit numbers in between of text's or numbers.

Tried VBA CODE to extract numbers and text. But for numbers they were all extracted together without space so cant do anything with them.

Function GetNumber(CellRef As String) 
    Dim StringLength As Integer
    StringLength = Len(CellRef)
    For i = 1 To StringLength
    If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
    Next i
    GetNumber = Result
End Function
 Function GetText(CellRef As String) 
    Dim StringLength As Integer
    StringLength = Len(CellRef)
    For i = 1 To StringLength
    If Not (IsNumeric(Mid(CellRef, i, 1))) Then Result = Result & Mid(CellRef, i, 1)
    Next i
    GetNumber = Result
End Function

Would anyone be kind enough to help?

1 Answers

Quick example (untested)

dim rowNum as long
for rowNum = 1 to 5
    dim splitArr as variant
    splitArr = split(cells(rowNum, 1).value, " ")
    dim elementNum as long
    for elementNum = lbound(splitArr) to ubound(splitArr)
        checkVal = splitArr(elementNum)
        Select case True
            Case left(checkVal,1)=2 and len(checkVal)=4
                'do something
            Case left(checkVal,1)=2 and len(checkVal)=7
                'do something
            Case left(checkVal,1)=4 and len(checkVal)=7            
                'do something
        End select
    next elementNum
next rowNum
Related