Option Explicit
Sub exa2()
Dim FSO As Object
Dim wb As Workbook
Dim wks As Worksheet
Dim strFileName As String
Const SH_NAME As String = "TEMPLATE" '<--Change to suit
'// Check to ensure the sheet exists //
On Error Resume Next
Set wks = ThisWorkbook.Worksheets(SH_NAME)
On Error GoTo 0
If wks Is Nothing Then
MsgBox SH_NAME & " is missing!", 0, vbNullString
Exit Sub
End If
'// Ensure both suggested filename and foldername are legal //
If Not (IsLegalNam(wks.Range("A2").Value) And IsLegalNam(wks.Range("B2").Value)) Then
MsgBox "On of the suggested names is illegal", vbExclamation, vbNullString
Exit Sub
End If
strFileName = wks.Range("B2").Value
'// Change to suit //
If Not Right(strFileName, 4) = ".xls" Then
strFileName = strFileName & ".xls"
End If
Set FSO = CreateObject("Scripting.FileSystemObject")
With FSO
If Not .FolderExists(ThisWorkbook.Path & "\" & wks.Range("A2").Text) Then
.CreateFolder (ThisWorkbook.Path & "\" & wks.Range("A2").Text)
Set wb = Workbooks.Add
wb.SaveAs ThisWorkbook.Path & "\" & wks.Range("A2").Text & "\" & wks.Range("B2").Text
wb.Close False
End If
End With
End Sub
Function IsLegalNam(NameInputted As String, Optional IsFileName As Boolean = True) As Boolean
Dim IllegalCharacters As Variant
Dim i As Long
IsLegalNam = True
IllegalCharacters = IIf(IsFileName, _
Array("/", "\", ":", "*", "?", """", "<", ">", "|", "!"), _
Array(":", "/", "\", "?", "*", "[", "]", "!") _
)
For i = LBound(IllegalCharacters) To UBound(IllegalCharacters)
If CBool(InStr(1, NameInputted, IllegalCharacters(i))) Then
IsLegalNam = False
Exit Function
End If
Next
If Not IsFileName And (Len(NameInputted) > 31 Or UCase(NameInputted) = "HISTORY") Then
IsLegalNam = False
End If
End Function