Apply code to all sheets

dcrighton

New Member
Joined
Nov 24, 2014
Messages
31
Sub TrimEText()
' This module will trim extra spaces from BOTH SIDES and excessive spaces from inside the text.
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
Dim MyCell As Range
Selection.Cells.SpecialCells(xlCellTypeConstants, 23).Select
For Each MyCell In Selection.Cells
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", "")
Next
Next sh
End Sub

This doesn't seem to remove spaces on all sheets in my excel file just the sheet I'm viewing, any suggestions?
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Hi and welcome to the forum.

You are referencing MyCell to a selection which has a sheet parent object so your code will only do those cells, but multiple times.

Selection is rarely required in VBA, it is an artifact of learning from the macro recorder which records clicking on a cell as a selection.

If you want to change all data on all sheets try:

Code:
Sub Cull_Spaces()
Dim oRegex As Object, rTest As Range, rCell As Range
Set oRegex = CreateObject("vbscript.regexp")
With oRegex
    .Pattern = "\s{2,20}"
    .Global = True
    For Each sh In ActiveWorkbook.Sheets
        On Error Resume Next
        Set rTest = sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
        On Error GoTo 0
        If Not rTest Is Nothing Then
            For Each rCell In sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
                rCell.Value = Trim(.Replace(rCell.Value, " "))
            Next
        End If
        Set rTest = Nothing
    Next
End With
Set oRegex = Nothing
End Sub

This will replace 2-20 spaces with a single space as well as removing leading and trailing spaces.

ps: this was a quick hack without much testing so try it on a copy of your data first.
pps: I think that you only need a 3 rather than 23 in the SpecialCells method/
 
Upvote 0
it works great for removing spaces before and after text but I also want any single space within text removed and any double spaces or greater dropped down to single spaces.

ex. 12 907 -- after -- 12907
ex. the___ dog -- after -- The dog
 
Upvote 0
The code already reduces groups of spaces (from 2 to 20) to a single space within the cell contents.
What do you mean by "any single space within text removed"? Do you want
"The Quick Brown Fox"
to become
"TheQuickBrownFox"?
 
Upvote 0
Working on the assumption that the original code you posted works (provides the desired result) for just the currently viewed page...

Just remove this line
Selection.Cells.SpecialCells(xlCellTypeConstants, 23).Select

And change this line
For Each MyCell In Selection.Cells
to
For Each MyCell In sh.Cells.SpecialCells(xlCellTypeConstants, 23)



Also, though not 'wrong' persay...
The Dim MyCell As Range should be done at the top (not inside the For Each loop).
 
Upvote 0
Jonmo1 I have tried your suggestions but I get an error message "Unable to get the SpecialCells property of the Range class"


I appreciate your help,
DC
 
Last edited:
Upvote 0
Yes Teeroy that is exactly what I want it to do on all sheets :) and thank you for helping me out. I'll keep trying t figure it out I'm sure its just some minor change to your code to get what I want.

DC
 
Upvote 0
You can amend the previous code to do what you have asked by changing the pattern and replace, e.g:

Code:
Sub Cull_Spaces()
Dim oRegex As Object, rTest As Range, rCell As Range
Set oRegex = CreateObject("vbscript.regexp")
With oRegex
    .Pattern = "\s*"
    .Global = True
    For Each sh In ActiveWorkbook.Sheets
        On Error Resume Next
        Set rTest = sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
        On Error GoTo 0
        If Not rTest Is Nothing Then
            For Each rCell In sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
                rCell.Value = Trim(.Replace(rCell.Value, ""))
            Next
        End If
        Set rTest = Nothing
    Next
End With
Set oRegex = Nothing
End Sub

However since the requirement has changed you can use a simplified code:

Code:
Sub Cull_Spaces2()
Dim sh, rCell As Range, rTest As Range
For Each sh In ActiveWorkbook.Sheets
    On Error Resume Next
    Set rTest = sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
    On Error GoTo 0
    If Not rTest Is Nothing Then
        For Each rCell In sh.UsedRange.SpecialCells(xlCellTypeConstants, 23)
            rCell.Value = Replace(rCell.Value, " ", "")
        Next
    End If
    Set rTest = Nothing
Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,216,085
Messages
6,128,732
Members
449,465
Latest member
TAKLAM

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