Replacing whitespace in worksheet names with an underscore

Impos2004

New Member
Joined
Jun 10, 2013
Messages
15
Hi,

I'm not very competent with VBA and am having trouble with a script that creates hyperlinks to other worksheets in the workbook.

The worksheet names are dictated externally and occasionally contain white spaces, which means that the hyperlinks that my VBA creates don't work for those tabs. I would like to write a line or two of code to replace all of the whitespaces in all of the worksheet names with underscores, which will solve the hyperlink issue.

Does anyone know how I can do this?

Many thanks for your time

David
 

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.
Welcome to the Board!

This bit of code should do what you want:
Code:
    Dim ws As Worksheet
      
    For Each ws In ActiveWorkbook.Sheets
        ws.Name = Replace(ws.Name, " ", "_")
    Next ws
 
Upvote 0
Why do you need to replace the spaces? If your code to add the hyperlinks encloses the sheet name in single quotes (e.g. use 'sheet with spaces' in the SubAddress) then the hyperlink should work.
 
Upvote 0
Perfect, thank you!

The reason I can't use single quotes was because the worksheet names are variable, so it is looking them up itself. There could be dozens of them with different and unpredicable names.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,875
Messages
6,122,042
Members
449,063
Latest member
ak94

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