I have a function that gets a name for a new workbook, tries to open that workbook in the current folder and, if it can't do this, create a new workbook and save it in the current folder (and I am trying to save it with the name for the file, passed to the function). Looks like the workbook is created, as it opens (but with name "pasta11", which isn't what I expected) but it isn't saved anywhere.
Public Function SaveNewWorkbookToRelativePath(nameOfNewFile As String)
Dim relativePath As String
relativePath = ThisWorkbook.Path & "\" & nameOfNewFile
On Error GoTo NoSheetHandler
Workbooks.Open (relativePath)
Exit Function
NoSheetHandler:
Workbooks.Add.SaveAs Filename = relativePath, FileFormat = 52
End Function
The error is Runtime error 1004: application or object defined error.
A Test
Sub OpenMewTEST()
OpenMew "Test1"
End Sub
The Method (Sub)
Sub OpenMew(ByVal BaseName As String)
Const PROC_TITLE As String = "Open Macro-Enabled Workbook"
On Error GoTo ClearError
Const FILE_EXTENSION As String = ".xlsm" ' fixed
Dim fName As String: fName = BaseName
If StrComp(Right(fName, Len(FILE_EXTENSION)), FILE_EXTENSION, _
vbTextCompare) <> 0 Then
fName = fName & FILE_EXTENSION
End If
Dim wb As Workbook:
On Error Resume Next
Set wb = Workbooks(fName)
On Error GoTo ClearError
If Not wb Is Nothing Then
MsgBox "A workbook named """ & fName & """ is already open.", _
vbExclamation, PROC_TITLE
Exit Sub
End If
Dim fPath As String:
fPath = ThisWorkbook.Path & Application.PathSeparator & fName
Dim CheckName As String: CheckName = Dir(fPath)
If Len(CheckName) = 0 Then
Set wb = Workbooks.Add(xlWBATWorksheet) ' single worksheet
Dim ErrNumber As Long, ErrDescription As String
On Error Resume Next
wb.SaveAs fPath, xlOpenXMLWorkbookMacroEnabled ' 52
ErrNumber = Err.Number
ErrDescription = Err.Description
On Error GoTo ClearError
If ErrNumber = 0 Then
MsgBox "Workbook """ & fName & """ created and saved.", _
vbInformation, PROC_TITLE
Else
If Not wb Is Nothing Then
wb.Close SaveChanges:=False
End If
MsgBox "Run-time error '" & ErrNumber & "':" & vbLf & vbLf _
& ErrDescription & vbLf & vbLf & "Could not save as """ _
& fPath & """.", vbCritical, PROC_TITLE
End If
Else
Workbooks.Open fPath
MsgBox "Workbook """ & fName & """ opened.", _
vbInformation, PROC_TITLE
End If
ProcExit:
Exit Sub
ClearError:
MsgBox "Run-time error '" & Err.Number & "':" & vbLf & vbLf _
& Err.Description, vbCritical, PROC_TITLE
Resume ProcExit
End Sub