VBA code to remove leading and trailing spaces from cells in table now failing

BlondieC

New Member
Joined
Feb 9, 2016
Messages
41
Hi, this code was working and now is failing and I'm not sure why. It was set to trim all leading and training spaces from all cells in MasterTbl. The line it fails on is in red in the below code. The following error message is returned: Run-time error '13': Type mismatch.

Code:
Sub RemoveAllSpaces()     'Macro Purpose: To trim all excess spaces out of cells.  This
     'eliminates issues where users have cleared the cell with a space,
     'and elimates all extra spaces at the beginning or end of a string
     
    Application.ScreenUpdating = False
     
    Dim cl As Variant
     
     'Loop through cells removing excess spaces
      For Each cl In ActiveSheet.Range("MasterTbl")
[COLOR=#ff0000][B]        If Len(cl) > Len(WorksheetFunction.Trim(cl)) Then[/B][/COLOR]
            cl.Value = WorksheetFunction.Trim(cl)
        End If
    Next cl
        
    Application.ScreenUpdating = True
    
End Sub


MasterTbl data from columns A:K with D as a hidden column:
This data at this point needs a lot of cleanup done but as step one I want leading and trailing spaces removed.

Old Box#Civic#UnitStreet NameStreet TypeDirectionLast NameFirst NameConvenience BoxComments
1660CENTRAL LAMBTON FAMILY HEALTH TEAM269
1247OPTIMIST CLUB156
2001MOVEDCHECKZAVITZDONALD
518CHECKADDRESS/CONFIRMUNITBROOKSGERRY
843408ALBANYSTHARTLEYLAWRENCE
1004410ALBANYST621 TECHNOLOGIES IN.
929413CALBANYSTSHAKERS LOUNGE
1090430ALBANYSTHOBEN DENTISTRY
2094436ALBANYSTBUDS PIZZALORNE DOUGLAS
1451437ALBANYSTDOUGLASLORNE
134321ALBANYST.SYKESSTEVE
310413AALBANYOIL RIG RESTAURANT
1209422ALBANYPETROLIA INSTANT PRINTRANDY DRYDAK

<tbody>
</tbody>


Thank you!
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
I just tried running the code in smaller chunks and it looks like it was failing when it encountered this:
#NAME?

<tbody>
</tbody>
in one of the cells. Nothing worse than working with really dirty data.
 
Upvote 0
BlondieC,

1. What version of Excel, and, Windows are you using?

2. Are you using a PC or a Mac?


Here is a macro solution for you to consider, that does not loop thru all the cells in the active worksheet that contains the MasterTbl.

Sample raw data with the column D not hidden for display purposes:


Excel 2007
ABCDEFGHIJ
1Old Box#Civic#UnitStreet NameStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247OPTIMIST CLUB 156
42001MOVEDCHECKZAVITZDONALD
5518CHECKADDRESS/CONFIRMUNITBROOKSGERRY
6843408ALBANYSTHARTLEYLAWRENCE
71004410ALBANYST621 TECHNOLOGIES IN.
8929413CALBANYST SHAKERS LOUNGE
91090430ALBANYSTHOBEN DENTISTRY
102094436ALBANYSTBUDS PIZZALORNE DOUGLAS
111451437ALBANYSTDOUGLASLORNE
12134321ALBANYST.SYKESSTEVE
13310413AALBANYOIL RIG RESTAURANT
141209422ALBANYPETROLIA INSTANT PRINTRANDY DRYDAK
15
Sheet1


And, if we hide column D before running the macro:


Excel 2007
ABCEFGHIJ
1Old Box#Civic#UnitStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247OPTIMIST CLUB 156
42001MOVEDZAVITZDONALD
5518CHECKUNITBROOKSGERRY
6843408STHARTLEYLAWRENCE
71004410ST621 TECHNOLOGIES IN.
8929413CST SHAKERS LOUNGE
91090430STHOBEN DENTISTRY
102094436STBUDS PIZZALORNE DOUGLAS
111451437STDOUGLASLORNE
12134321ST.SYKESSTEVE
13310413AOIL RIG RESTAURANT
141209422PETROLIA INSTANT PRINTRANDY DRYDAK
15
Sheet1


Then we run the macro, and, then unhide column D, and, we get this:


Excel 2007
ABCDEFGHIJ
1Old Box#Civic#UnitStreet NameStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247OPTIMIST CLUB156
42001MOVEDCHECKZAVITZDONALD
5518CHECKADDRESS/CONFIRMUNITBROOKSGERRY
6843408ALBANYSTHARTLEYLAWRENCE
71004410ALBANYST621 TECHNOLOGIES IN.
8929413CALBANYSTSHAKERS LOUNGE
91090430ALBANYSTHOBEN DENTISTRY
102094436ALBANYSTBUDS PIZZALORNE DOUGLAS
111451437ALBANYSTDOUGLASLORNE
12134321ALBANYST.SYKESSTEVE
13310413AALBANYOIL RIG RESTAURANT
141209422ALBANYPETROLIA INSTANT PRINTRANDY DRYDAK
15
Sheet1


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

Code:
Sub RemoveLeadingTrailingSpaces()
' hiker95, 02/26/2016, ME9242394
With ActiveSheet
  With .Range("MasterTbl")
    .Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
  End With
End With
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm, and, answer the "do you want to enable macros" question as "yes" or "OK" (depending on the button label for your version of Excel) the next time you open your workbook.

Then run the RemoveLeadingTrailingSpaces macro.


The word wrapping in the YELLOW cells is only happening in the MrExcel display area, and, not in the worksheet.
 
Last edited:
Upvote 0
Rich (BB code):
Sub RemoveLeadingTrailingSpaces()
' hiker95, 02/26/2016, ME9242394
With ActiveSheet
  With .Range("MasterTbl")
    .Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
  End With
End With
End Sub
I like that method of controlling the "0 if the cell is empty" problem.
 
Upvote 0
I like that method of controlling the "0 if the cell is empty" problem.

Rick Rothstein,

Thank you very much.

I usually keep track of where I find gems like this, but, in this case, I did not.

I am going to say that the code was probably one of your gems that is in my archives.

Thanks again.
 
Upvote 0
Rick Rothstein,

Thank you very much.

I usually keep track of where I find gems like this, but, in this case, I did not.

I am going to say that the code was probably one of your gems that is in my archives.
The structure of the Evaluate function looks to be mine, but the use of REPT like that is not. My "go to" method to handle the problem was (before I saw your treatment, that is :wink:) this...

Code:
[table="width: 500"]
[tr]
	[td].Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),[COLOR="#FF0000"]IF(" & .Address & "="""",""""," & .Address & ")[/COLOR])")[/td]
[/tr]
[/table]
 
Last edited:
Upvote 0
Rick Rothstein,

I just checked your new code line, in my macro with the displayed raw data, and, it returned the same results.

Thanks again for another gem for my archives.
 
Upvote 0
Hi and thank you to everyone for stopping in to help. Today is my first day to look at the suggestions and try them out. I'm working on this for another department so I fit it in when I can and month-end reports consumed most of my time before getting back to this.

I am using Excel 2013 and Windows 7 Enterprise.

I do have this workbook saved as macro enabled and have a test version to work in. Going to try out the suggestions now.

BlondieC,

1. What version of Excel, and, Windows are you using?

2. Are you using a PC or a Mac?


Here is a macro solution for you to consider, that does not loop thru all the cells in the active worksheet that contains the MasterTbl.

Sample raw data with the column D not hidden for display purposes:

Excel 2007
ABCDEFGHIJ
1Old Box#Civic#UnitStreet NameStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247 OPTIMIST CLUB 156
42001MOVEDCHECKZAVITZ DONALD
5518CHECK ADDRESS/CONFIRMUNITBROOKS GERRY
6843408ALBANYSTHARTLEYLAWRENCE
71004410ALBANYST621 TECHNOLOGIES IN.
8929413CALBANY ST SHAKERS LOUNGE
91090430ALBANYSTHOBEN DENTISTRY
102094436 ALBANYST BUDS PIZZALORNE DOUGLAS
111451437ALBANYSTDOUGLASLORNE
12134321ALBANYST.SYKESSTEVE
13310413AALBANYOIL RIG RESTAURANT
141209422ALBANYPETROLIA INSTANT PRINT RANDY DRYDAK
15

<colgroup><col style="width: 25pxpx"><col><col><col><col><col><col><col><col><col><col></colgroup><thead>
</thead><tbody>
</tbody>
Sheet1



And, if we hide column D before running the macro:

Excel 2007
ABCEFGHIJ
1Old Box#Civic#UnitStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247 OPTIMIST CLUB 156
42001MOVEDZAVITZ DONALD
5518CHECKUNITBROOKS GERRY
6843408STHARTLEYLAWRENCE
71004410ST621 TECHNOLOGIES IN.
8929413C ST SHAKERS LOUNGE
91090430STHOBEN DENTISTRY
102094436ST BUDS PIZZALORNE DOUGLAS
111451437STDOUGLASLORNE
12134321ST.SYKESSTEVE
13310413AOIL RIG RESTAURANT
141209422PETROLIA INSTANT PRINT RANDY DRYDAK
15

<colgroup><col style="width: 25pxpx"><col><col><col><col><col><col><col><col><col></colgroup><thead>
</thead><tbody>
</tbody>
Sheet1



Then we run the macro, and, then unhide column D, and, we get this:

Excel 2007
ABCDEFGHIJ
1Old Box#Civic#UnitStreet NameStreet TypeDirectionLast NameFirst NameConvenience BoxComments
21660CENTRAL LAMBTON FAMILY HEALTH TEAM269
31247OPTIMIST CLUB156
42001MOVEDCHECKZAVITZDONALD
5518CHECKADDRESS/CONFIRMUNITBROOKSGERRY
6843408ALBANYSTHARTLEYLAWRENCE
71004410ALBANYST621 TECHNOLOGIES IN.
8929413CALBANYSTSHAKERS LOUNGE
91090430ALBANYSTHOBEN DENTISTRY
102094436ALBANYSTBUDS PIZZALORNE DOUGLAS
111451437ALBANYSTDOUGLASLORNE
12134321ALBANYST.SYKESSTEVE
13310413AALBANYOIL RIG RESTAURANT
141209422ALBANYPETROLIA INSTANT PRINTRANDY DRYDAK
15

<colgroup><col style="width: 25pxpx"><col><col><col><col><col><col><col><col><col><col></colgroup><thead>
</thead><tbody>
</tbody>
Sheet1



Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

Code:
Sub RemoveLeadingTrailingSpaces()
' hiker95, 02/26/2016, ME9242394
With ActiveSheet
  With .Range("MasterTbl")
    .Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
  End With
End With
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm, and, answer the "do you want to enable macros" question as "yes" or "OK" (depending on the button label for your version of Excel) the next time you open your workbook.

Then run the RemoveLeadingTrailingSpaces macro.


The word wrapping in the YELLOW cells is only happening in the MrExcel display area, and, not in the worksheet.
 
Upvote 0
hiker95 this worked like a charm! Thank you so much! And the additional comments and conversation help me understand how it works. This is one more thing to help the end-users of this workbook I'm creating for them. Much appreciated. :biggrin:
 
Last edited:
Upvote 0

Forum statistics

Threads
1,215,831
Messages
6,127,142
Members
449,363
Latest member
Yap999

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