UPDATE #2: I have split the line from Set ExcelBook = Workbooks.Add
to 2 separate lines (Workbooks.Add
and Set ExcelBook = ActiveWorkbook
) and am still randomly receiving the error. It does not happen every time, but when it does it directs me to the line Workbooks.Add
(still receiving the same type mismatch error).
Sub NewWorkbook(CompanyName As String, OutputDirectory As String, Scenario As String)
Dim ExcelBook As Workbook
Dim CopyArea As Range
Set CopyArea = Range("CopyArea")
Workbooks.Add
Set ExcelBook = ActiveWorkbook
CopyArea.Copy
ExcelBook.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
ExcelBook.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteFormats
ExcelBook.Sheets("Sheet1").Columns(2).EntireColumn.Delete
ExcelBook.Sheets("Sheet1").Rows(6).EntireRow.Delete
ExcelBook.Sheets("Sheet1").Cells.EntireColumn.AutoFit
Application.DisplayAlerts = False
ExcelBook.Close SaveChanges:=True, Filename:=OutputDirectory + "\" + Replace(Replace(Replace(CompanyName, "\", ""), "/", ""), ":", "") + " - " + Scenario + ".xlsx"
Application.DisplayAlerts = True
Set ExcelBook = Nothing
Set CopyArea = Nothing
End Sub
UPDATE: I have re-worked the code to remove select/activate, but I am still getting the random mismatch error. When I do receive the error, it does seem to be creating the new workbook, but stops after that (after receiving the error and selecting 'End', there is a blank workbook that was not there before).
ORIGINAL DESCRIPTION: I am receiving a mismatch error in the above code on line 'Set ExcelBook = Workbooks.add'. What is strange is that the error does not occur every time (I can't seem to find any pattern on why it happens sometimes and not others).
I have another macro that calls the below code in a 'For' loop. Sometimes it will finish successfully, other times it will error out on the 1st iteration, other times on the 5th iteration, etc.
Any thoughts?