I'm now trying to achieve the same on a worksheet and need it to apply to all cells between C2:C30. However, some of those cells will only contain 1 word so is there a way I can achieve it without it throwing an error if there is only 1 word anyway, i.e. get it to ignore cells with only 1 word?
The only time Split would have a problem is if the value it is splitting contains no text... Split will work fine if the value only has one word. If you want to protect against an empty value, simply concatenate a blank space onto the variable so it has a blank space to find...
Code:
Sub Test()
Dim Rng As Range
For Each Rng In Range("C2:C30")
Rng = Split(Rng & " ")(0)
Next
End Sub
Of course, since the range is fixed in size, we can also do this more compactly with just a single line of code...
Code:
Sub Test2()
[C2:C30] = [IF({1},LEFT(C2:C30,FIND(" ",C2:C30&" ")-1))]
End Sub
We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel
Which adblocker are you using?
Disable AdBlock
Follow these easy steps to disable AdBlock
1)Click on the icon in the browser’s toolbar. 2)Click on the icon in the browser’s toolbar. 2)Click on the "Pause on this site" option.
Go back
Disable AdBlock Plus
Follow these easy steps to disable AdBlock Plus
1)Click on the icon in the browser’s toolbar. 2)Click on the toggle to disable it for "mrexcel.com".
Go back
Disable uBlock Origin
Follow these easy steps to disable uBlock Origin
1)Click on the icon in the browser’s toolbar. 2)Click on the "Power" button. 3)Click on the "Refresh" button.
Go back
Disable uBlock
Follow these easy steps to disable uBlock
1)Click on the icon in the browser’s toolbar. 2)Click on the "Power" button. 3)Click on the "Refresh" button.