0 votes
in VBA by Beginner (2 points)
How to save file with special characters in file name Save As

Ex. --Sheet2.range(B2)_Sheet2.range(BY)_ABCD

I've tried multiple times but code is not accepting special characters

2 Answers

+2 votes
by Expert (892 points)

You have to use valid characters only so I suggest you use the following UDF that gives you the valid name so as to avoid any errors

Sub Test_CleanName_UDF()
    Debug.Print ValidName("my%workbook\&<>.*name")
End Sub

Function ValidName(ByVal sName As String) As String
    Dim i As Long
    For i = 1 To Len(sName)
        If Mid(sName, i, 1) = "]" Or Mid(sName, i, 1) Like "[! 0-9A-Za-z^&'@{}[,$=!#()%.+~_-]" Then Mid(sName, i, 1) = "*"
    Next i
    ValidName = Replace(sName, "*", "")
End Function


0 votes
by Skilled (749 points)

Try this:

ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & Sheet2.Range("B2") & "_" & Sheet2.Range("BY") & "_ABCD.xlsm"

Make sure cells B2 and BY don't contain invalid filename characters.

by Beginner (4 points)


what could "BY" contains ?

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Getting Started
VBA Cheat Sheets (On Sale Now)

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

Looking for something else? Hire our professional VBA Help, instead.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and answers. All you have to do is post and you could get rewarded, like these members:

ParserMonster $25 Amazon Gift Card
Hightree $10 Amazon Gift Card
Thales1 $10 Amazon Gift Card
runfunke $10 Amazon Gift Card
coolag $10 Amazon Gift Card
Siew Hun $10 Amazon Gift Card

So, why don't you join us? It really is an encouraging way to motivate members in our VBA and Python community.


For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.