Question posted 2011 · +3 upvotes
I am writing a fairly large macro
- which ends by saving the workbook with a name that the user inputted earlier on.
- I am using the title of the sheet for this, so I need to strip out any reserved characters that will throw up file system errors
(/*|?:<>").
I would like to avoid having to use a large number of Replace() statements, so is there any way to replace multiple characters with an underscore in one statement – something more like a regexp?
Thanks all!
Accepted answer +7 upvotes
Happily you will find that most of these characters are invalid already as sheet name characters, ie *?[] etc
But as you have said already, use a regexp 🙂
Something like below to return True for valid strings, False for invalid ones.
I have added your items above, escaping special characters as needed.
[Updated: added replacement Function]
Sub TestCleanNames()
Dim StrArr()
Dim StrTst
StrArr = Array("Am i ok", "Sheet||a", "audited??", "Sheet1")
For Each StrTst In StrArr
MsgBox StrTst & " = " & ValidSheetName(CStr(StrTst)) & vbNewLine & CleanSheetName(CStr(StrTst))
Next
End Sub
valid name function
Function ValidSheetName(strIn As String) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Pattern = "[<>*\/?|]"
ValidSheetName = Not objRegex.test(strIn)
End Function
clean function
Function CleanSheetName(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[<>*\/?|]"
CleanSheetName = .Replace(strIn, "_")
End With
End Function
3 code variants in this answer
- Variant 1 — 8 lines, starts with
Sub TestCleanNames() - Variant 2 — 6 lines, starts with
Function ValidSheetName(strIn As String) As Boolean - Variant 3 — 9 lines, starts with
Function CleanSheetName(strIn As String) As String
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- Can a VBA function in Excel return a range? +36 (2009)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
excel-vba solutions on this site
.