I am trying to split a value inside a cell at the last space. For example, I want Abbey Road 4
split to Abbey Road
and 4
I need this to be done with VBA, not a Formula, as I need to delete the original Column afterwards.
Look at INSTRREV to find the last occurrence of a string within a string. https://msdn.microsoft.com/en-us/library/hsxyczeb(v=vs.84).aspx
Sub Test()
SplitText ThisWorkbook.Worksheets("Sheet1").Range("A1:A11")
End Sub
Sub SplitText(SrcRange As Range)
Dim rCell As Range
For Each rCell In SrcRange.Cells
rCell.Offset(, 1) = Left(rCell, InStrRev(rCell, " ") - 1)
rCell.Offset(, 2) = Mid(rCell, InStrRev(rCell, " ") + 1)
Next rCell
End Sub
Here is a variation on the answer from Darren Bartrup-Cook ...
Assume cell A2 has the text Some text with spaces
in it, below will put Some text with
in C2 and spaces
in D2
'Get text from A2
theText = Cells(2, 1).Value
'Get text to the left of last space
newTextLeft = Left(theText, InStrRev(theText, " ") - 1)
Cells(2, 3).Value = newTextLeft
'Get text to right of last space
newTextRight = Mid(theText, InStrRev(theText, " ") + 1)
Cells(2, 4).Value = newTextRight
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.