用于将工作簿中的每个工作表保存为CSV文件的宏

时间:2016-04-01 19:51:17

标签: excel macos vba excel-vba

首先请允许我说,我已经谷歌搜索了几个小时并尝试了我能找到的每一个在线代码,所以不要以为我没有尝过才会问...

出于某种原因,我发现每一个都有错误。我只想要一个宏将一个.xlsm工作簿的每张表保存到.csv文件。我最好能够让宏创建一个弹出窗口,我可以在其中选择CSV文件的目标路径。

这将使用Office 2016 for Mac。

具体来说,这是我刚试过的一个:

    Sub SaveAllSheetsAsCSV2()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

' save for each sheet
For Each Sheet In Sheets

    OutputFile = OutputPath & "/" & Sheet.Name & ".csv"

    ' make a copy to create a new book with this sheet
    ' otherwise you will always only get the first sheet
    Sheet.Copy
    ' this copy will now become active
    ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close
Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
    "Source: " & Err.Source & " " & vbCrLf & _
    "Number: " & Err.Number & " " & vbCrLf & _
    "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

我尝试改变的一件事是这一行:

OutputFile = OutputPath & "/" & Sheet.Name & ".csv"

因为“/”最初是“\”而我正在使用mac所以我认为值得一试。两者都没有。

0 个答案:

没有答案