Preserving Range data Type while trimming trailing spaces.

cyberwolf

New Member
Joined
Oct 5, 2007
Messages
24
Office Version
  1. 365
Platform
  1. Windows
I found this thread in my search Trim Column in VBA and was able to convert Rick Rothstein's code to loop through all of the columns in a worksheet. Code will be listed below. Trouble is We have columns that have data with leading zero's, and, this code see to convert each column to general if it looks like a number. Is there anyway to preserve the existing format and still trim spaces?

VBA Code:
Sub TrimColumn()
Dim Addr As String
Dim lstCol As Long, lstRow As Long
Dim varCol As Variant
lstCol = Cells(1, Columns.Count).End(xlToLeft).Column
lstRow = Cells(Rows.Count, "A").End(xlUp).Row
For varCol = 1 To lstCol
Addr = Range(Cells(2, varCol), Cells(lstRow, varCol)).Address
Range(Addr) = Evaluate("IF(" & Addr & "="""","""",TRIM(" & Addr & "))")
Next varCol
End Sub
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
As far as I can see this code only removes spaces at the beginning and end of a text string. If you have hard coded zeros in a cell, this shouldn't remove those.
 
Upvote 0
As far as I can see this code only removes spaces at the beginning and end of a text string. If you have hard coded zeros in a cell, this shouldn't remove those.
It wasn't removing them. The problem was the data is exported from a dataset using a macro. The column in question was actually set to General. But the data was pasted in as text. So when that trim function was run on it. Once the data was trimmed Excel looked at the column as a General data type column and the leading zeros were dropped. Either way I was able to find a work around.
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,177
Members
453,021
Latest member
Justyna P

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