Script to remove the first and/or last character of string if they are a space

Oliver Dewar

Board Regular
Joined
Apr 17, 2011
Messages
201
Simple question (not sure if the script will be though!)

I need to remove any spaces that may appear either as the first or last character entered in a textbox on a userform.

I'll put the script into the exit event.

Note: the user may well not enter a space as the first or last character. This is just to clip the value back to words with only internal spaces so that the value can be cross referrenced against our database. At the moment a stray space will cause a duplicate to get past our checks and destroy the world (yes, the stakes are high on this one...)

Cheers!
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
You can use trim, for example

Code:
Private Sub CommandButton1_Click()
Range("A1") = Trim(TextBox1.Value)
End Sub

Which will trim off and superfluous spaces at the beginning/end of the value in a textbox
 
Upvote 0
If you want to replicate the action of the Excel worksheet function TRIM (which replaces multiple sequential instances of spaces within a string, then you can alternatively use the WorksheetFunction.Trim (it also removes leading/trailing spaces like the VBA function Trim that Dave used):

Code:
TextBox1.Value = Application.WorksheetFunction.Trim(TextBox1.Value)
 
Upvote 0

Forum statistics

Threads
1,224,527
Messages
6,179,345
Members
452,907
Latest member
Roland Deschain

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