I'm trying to split my column so that the names
James John Doe
Comes out as only
James John
Using the below formula but it only leaves the first name, where I want it to split at the second occurrence of "space".
Sub Split1()
Dim r As Range
For Each r In Range("A2:A" & Cells(Rows.count, "A").End(xlUp).Row).Cells.SpecialCells(xlCellTypeConstants)
r.Value = Split(r.Value, " ")(0)
Next r
Can anyone help me out?
Thanks
There are a few ways you can turn a three-word phrase into the first two words.
Let's start with your Split()
method. This function returns an array. Your particular method of attempting to access the index will only return a single word.
You can place into an array, then just combine the array elements:
For Each r In Range(...)
Dim retVal() As String
retVal = Split(r.Value)
r.Value = retVal(0) & " " & retVal(1)
Next r
You can remove the last word with Replace()
:
For Each r In Range(...)
r.Value = Replace(r.Value, Split(r.Value)(2), "")
Next
Or you can even use Regular Expressions:
With CreateObject("VBScript.RegExp")
.Pattern = "\s[^\s]+$"
For Each r in Range(...)
r.Value = .Replace(r.Value, "")
Next
End With
In Regular Expressions, \s
signifies a single space character, the [^...]
bracket means "Do not include", which we placed a \s
within the bracket, so that would match any non-space character , followed by the +
means 1 or more times, and finally the $
signifies the end of the string. Essentially, you are wanting to match a word [^\s]+
that is at the end of the string $
, preceeded by a space \s
, and remove it via the .Replace()
method. And you actually could also simply use the pattern \s\S+$
, which is essentially the same thing ( \S
means any non-space character when it's capitalized).
You may try to use left & find
to obtain the string value untill second space instead of split
function
Code modification:
Dim r As Range
Dim s As String, newText As String
Dim Length As Long
For Each r In Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Cells.SpecialCells(xlCellTypeConstants)
s = r.Value
Length = Application.WorksheetFunction.Find(" ", s, Application.WorksheetFunction.Find(" ", s) + 1)
r.Value = Left(s, Length)
Next r
Sample output:
Further way to extract the 1st and 3rd token of a split array
This approach profits from the advanced possibilities of Application.Index allowing to indicate any new row or columns order; the wanted columns are reflected here by the last 1-based (columns) argument Array(1, 3)
:
Function GetFirstLast(s As String) As String
GetFirstLast = Join(Application.Index(Split(s), 0, Array(1, 3)))
End Function
Example call:
Debug.Print GetFirstLast("James John Doe")
resulting in
James Doe
in the VB Editor's immediate window.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.