使用Excel宏将OS导出到OS X上的〜/ Desktop

时间:2016-01-27 05:42:35

标签: excel vba excel-vba csv

我正在尝试使用OS X(2015)上的Excel中的宏导出CSV。下面的代码以前工作过...但现在它失败了。不幸的是,我发现它的所有信息都是Windows独有的。

我可以定义确切的文件路径,但需要在任何OS X机器上工作,因此定义用户主目录很重要。

Sub export_csv()
    ' export csv to ~/Desktop
    user_dir = user_dir + MacScript("(do shell script ""cd ~; pwd "")")
    file_name = user_dir & "/Desktop/excel_export.csv"

    ActiveWorkbook.SaveAs Filename:=file_name, FileFormat:=xlCSV, CreateBackup:=False

End Sub

1 个答案:

答案 0 :(得分:0)

问题是,我没有任何OS X来测试它。但我认为如果您的工作簿中有很多表格,可能会出现一个问题。

Sub CSV()
Dim ws As Excel.Worksheet

Dim strDirectory As String
Dim strCurWB As String
Dim longCurFor As Long

strCurWB = ThisWorkbook.FullName
longCurFor = ThisWorkbook.FileFormat
' Store current details for the workbook

'get Path for User Desktp
strDirectory = CreateObject("WScript.Shell").specialfolders("Desktop") & "\"
'Loop though each Sheet in the Workbook
For Each ws In ThisWorkbook.Worksheets
    Sheets(ws.Name).Copy
    ActiveWorkbook.SaveAs Filename:=strDirectory & ThisWorkbook.Name & "-" & ws.Name & ".csv", FileFormat:=xlCSV
    ActiveWorkbook.Close savechanges:=False
    ThisWorkbook.Activate
Next

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=strCurWB, FileFormat:=longCurFor
Application.DisplayAlerts = True
End Sub

我希望此代码示例可以帮助您,您可以接受一些OSX。