Remove special characters from text string.

S Oberlander

Board Regular
Joined
Nov 25, 2020
Messages
147
Office Version
  1. 365
Platform
  1. Windows
I have a macro that saves my excel file and names it based on the selected cell, however very often there are characters that cannot be part of a filename. I would like to simply remove those characters and proceed with saving. There may be slashes and/or colons and other special characters in the selected cell, however I do not know its location as it varies.
How can I do this?

Random example:
The selected cell contains "Sample 1/1/22: Ready"
I want my filename to contain "Sample 1122 Ready"
or perhaps replace special characters with underscore so I get "Sample 1_1_22_ Ready".
 

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
Here is a function that will by default replace the invalid characters with zero length strings. It also has an optional second argument that will allow you to replace the invalid characters with whatever character you want.

2022 OTM Arrivals Mexicali Airport Weekly (version 1).xlsb
AB
35Sample 1/1/22: ReadySample 1122 Ready
36Sample 1/1/22: ReadySample 1_1_22_ Ready
Sheet4
Cell Formulas
RangeFormula
B35B35=NoSpec(A35)
B36B36=NoSpec(A36,"_")


VBA Code:
Function NoSpec(s As String, Optional r As String)
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "[<>:""\/\|?*]"
    NoSpec = .Replace(s, IIf(Len(r) > 0, r, ""))
End With
End Function
 
Upvote 0
Solution
Cool!
So I did fn = NoSpec(ActiveCell, "_") and my code no longer stops for an invalid filename.
 
Upvote 0

Forum statistics

Threads
1,214,641
Messages
6,120,691
Members
448,978
Latest member
rrauni

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