Replace Space with Underscore Loop with VBA

jeran042

New Member
Joined
Jun 9, 2016
Messages
23
Good morning all,

I have a quick question, not actually a problem. I have a very simple piece of code that will replace all the spaces in a selection with underscores. I mainly use it to clean up header rows. My question is, based on the code below, is there a way that this can be done better? And is the error handling sufficient for what I am trying to accomplish?

Very much appreciated,

Code:
Sub Convert_Space_To_Underscore()

'Error handling
    On Error GoTo Error_Handler


    Dim sValue As String
    
    For Each CELL In Selection
        sValue = Trim(CELL.Value)
        sValue = Replace(sValue, " ", "_")
        CELL.Value = sValue
    Next CELL




Error_Handler:
            MsgBox "Error No. " & Err.Number & vbCrLf & "Description: " & Err.Description, vbExclamation, "Database Error"
            Err.Clear
            Exit Sub
    
End Sub
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
The only thing that see is the lack of Exit Sub immediately before the Error_Handler label.
As it is, you will always get a message, even if there isn't an error.
 
Last edited:
Upvote 0
Another way of doing it would be
Code:
Sub Convert_Space_To_Underscore()
With Selection
   .Value = Evaluate(Replace("if({1},substitute(trim(@),"" "",""_""),@)", "@", .Address))
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,897
Messages
6,175,271
Members
452,628
Latest member
dd2

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