Avoiding error on saving a file if there are unacceptable characters

ditto

New Member
Joined
Mar 21, 2009
Messages
20
I want to use the following code to create a new folder and save the document in it with a filename taken from two cells on a sheet. But there is a chance to put characters like "/" and ":" in these cells which will cause an error since these characters cannot be used in filenames. Can I modify the code given below so that such characters will automatically be changed to an underscore instead of causing the error?

Code:
Function dirExists(dirAndPath) As Boolean
Dim tempVar
On Error Resume Next
tempVar = Dir(dirAndPath & "\*.*", vbDirectory)
If Err = 0 And tempVar <> "" Then
    dirExists = True
End If
On Error GoTo 0
End Function

Sub SaveMe()
Dim fname As String
If Not dirExists("C:\Bill") Then MkDir "C:\Bill"
fname = Sheets("Sheet1").Range("A1").Value & Sheets("Sheet1").Range("A2").Value & ".xls"
ThisWorkbook.SaveAs Filename:="C:\Bill\" & fname
End Sub
 

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.
Yes they might contain a date, time or name of a month. Like: 01/03/2009 or March/2009 or 03/2009.
 
Upvote 0
Try

Code:
Sub SaveMe()
Dim fname As String
If Not dirExists("C:\Bill") Then MkDir "C:\Bill"
fname = Sheets("Sheet1").Range("A1").Value & Sheets("Sheet1").Range("A2").Value & ".xls"
fname = Replace(Replace(fname, "/", "-"), ":", "-")
ThisWorkbook.SaveAs Filename:="C:\Bill\" & fname
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,646
Messages
6,120,717
Members
448,985
Latest member
chocbudda

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