I am running a VBA macro in Excel 2016 for Mac. The macro works on Windows platforms with Excel 2016, and on Mac platforms with earlier than the 2016 version. The issue appears specific to Excel 2016 for Mac when trying to export a CSV.
The code is supposed to allow the user to click a button, which will then export an active worksheet to a CSV file. While a similar issue was documented here (Getting "method saveas of object _workbook failed" error while trying to save an XLSM as CSV), unfortunately while changing xlCSV
to 6
worked for them, this has not worked for me.
The code works up until the ActiveWorkbook.SaveAs Filename:=newFileName, FileFormat:=6, CreateBackup:=False
line, which then throws the error:
Run-time error '1004':Method 'SaveAs' of object '_Workbook' failed
If I change FileFormat
to 51
(.xlsx) or 53
(.xlsm) the code will successfully finish. However, if FileFormat
is set to 6
(.csv) the code will throw the error above. I am unable to SaveAs
xlCSV
or xlCSVMac
.
My full script is below:
Sub btnExportCSV_Click()
Dim oldFileName As String
Dim newFileName As String
Dim timeStamp As String
Dim fileAccessGranted As Boolean
Dim filePermissionCandidates
Dim wsPath As String
timeStamp = Format(Now, "yyyymmddhhmmss")
wsPath = Application.ThisWorkbook.Path
oldFileName = ThisWorkbook.FullName
newFileName = Mid(oldFileName, 1, InStrRev(oldFileName, ".") - 1) & timeStamp & ".csv"
' Check if software is Office 2016 for Mac
' Documentation for this comes from https://dev.office.com/blogs/VBA-improvements-in-Office-2016
#If MAC_OFFICE_VERSION >= 15 Then
filePermissionCandidates = Array(wsPath)
fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates)
#End If
Application.DisplayAlerts = False
Sheets("OfflineComments").Activate
Sheets("OfflineComments").Copy
ActiveWorkbook.SaveAs Filename:=newFileName, FileFormat:=6, CreateBackup:=False
ActiveWorkbook.Save
ActiveWindow.Close
MsgBox ("Offline comments exported to " & newFileName)
Application.DisplayAlerts = True
End Sub
I have tried:
- Adding a full path to the input/output file names
- Ensuring that version of Excel is checked for and permissions allowed by user
- Various file types for the
FileFormat
parameter, but as mentioned, only two types actually worked. - Trying the code mentioned in the above-linked article, which did not help (and which is why I am posting the original code here).