我正在运行Excel 2016 for Mac中的VBA宏。该宏适用于Windows平台上的Excel 2016以及早期版本的Mac平台。问题似乎出现在尝试导出CSV时,特定于Excel 2016 for Mac。
代码应该允许用户点击按钮,然后将活动工作表导出为CSV文件。虽然在这里记录了类似的问题(Getting "method saveas of object _workbook failed" error while trying to save an XLSM as CSV),但是,不幸的是,尽管将xlCSV
更改为6
对他们有用,但对我没有用。
代码工作正常,直到ActiveWorkbook.SaveAs Filename:=newFileName, FileFormat:=6, CreateBackup:=False
这一行,然后抛出以下错误:
运行时错误 '1004':对象'_Workbook'的方法'SaveAs'失败
如果我将FileFormat
更改为51
(.xlsx)或53
(.xlsm),则代码将成功完成。但是,如果FileFormat
设置为6
(.csv),代码将抛出上述错误。我无法将xlCSV
或xlCSVMac
保存为SaveAs
。
我的完整脚本如下:
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
我尝试过以下方法:
- 在输入/输出文件名中添加完整路径
- 确保检查了Excel的版本并允许用户权限
- 尝试使用不同的文件类型作为
FileFormat
参数,但只有两种类型实际上有效。 - 尝试使用上面链接文章中提到的代码,但没有帮助(这就是为什么我在这里发布原始代码的原因)。