Remove all but first word in Textbox

sharky12345

Well-known Member
Joined
Aug 5, 2010
Messages
3,422
Office Version
  1. 2016
Platform
  1. Windows
Can someone show me how to remove all words, characters and extra spaces from a Userform textbox with the exception of the first word?
 
Guys, can I ask another question please?

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?
Which code that has been posted for TextBox above do you think will error if the TextBox (or one of your cells) only had one word in it?
 
Upvote 0

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Try:
Code:
Sub Test()
    Dim rng As Range
    For Each rng In Range("C2:C30")
        If InStr(1, rng, " ") > 0 Then
            rng = Split(rng)(0)
        End If
    Next rng
End Sub
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
 
Upvote 0

Forum statistics

Threads
1,224,824
Messages
6,181,186
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

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.
Go back
Back
Top