• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

extract string based on the spaces in the string

ThrottleWorks

Excel Ninja
Hi,

I am trying to extract string based on the spaces in the string. Below is input and output for your reference.
Can anyone please suggest me a formula or VBA code to achieve this.

Input = Yahaha is a beautiful bike I love it
Output = Yahaha is a

Input = Yahaha is a beautiful bike I love
Output = Yahaha is a

Input = Yahaha is a beautiful bike I
Output= Yahaha is a

Input = Yahaha is a beautiful bike
Output= Yahaha is a

Input = Yahaha is a beautiful
Output= Yahaha is a

Input = Yahaha is a
Output= Yahaha is a

Input = Yahaha is
Output= Yahaha is

Input = Yahaha
Output= Yahaha
 
May be
Code:
Sub Test()
    Dim arr    As Variant
    Dim i      As Long

    arr = Range("A1:B" & Cells(Rows.Count, 1).End(xlUp).Row).Value
    For i = LBound(arr, 1) To UBound(arr, 1)
        On Error GoTo Skipper
        If InStr(arr(i, 1), " ") > 0 Then
            arr(i, 2) = Split(arr(i, 1), " ")(0) & " " & Split(arr(i, 1), " ")(1) & " " & Split(arr(i, 1), " ")(2)
            GoTo NextLoop
        Else
Skipper:
            arr(i, 2) = arr(i, 1)
        End If
NextLoop:
    Next i

    Range("A1:B" & Cells(Rows.Count, 1).End(xlUp).Row).Value = arr
End Sub
 
Back
Top