Clean spaces and returns when leaving a cell

rjplante

Well-known Member
Joined
Oct 31, 2008
Messages
574
Office Version
  1. 365
Platform
  1. Windows
I have a single 10 character block of text that is copied from another location and pasted into cell B2. It almost always contains leading and trailing spaces as well as a carriage return. I would like to have the user paste the value into the cell and when the hit tab, or the enter key to go to the next cell, the macro will automatically run to clean up the text. How do I get this to work. I have the following code in the individual worksheets code window. When I select the cell and tab/enter to the next cell, nothing happens.

I don't know what to do to get this to run and the cell selection is changed to cell B4.

Thanks for the help.

Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)


Dim snData As String
Dim newData As String


snData = Range("B2").Value


newData = Replace(Replace(snData, vbCrLf, ""), " ", "")


End Sub
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
Awesome, Thanks! Just had to change it to Range("B2") = Trim(Range("B2").value) and it all worked great.
 
Upvote 0

Forum statistics

Threads
1,223,952
Messages
6,175,594
Members
452,654
Latest member
mememe101

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