对于Mac,Excel 2011 VBA中是否有Scripting.FileSystemObject的替代方法?

时间:2011-01-13 07:53:03

标签: macos excel vba filesystemobject excel-vba-mac

How can I install/use “Scripting.FileSystemObject” in Excel 2011 for MAC?的答案似乎表明在Excel 2010中为mac使用Scripting.FileSystemObject可能

还有哪些替代可用,所以我可以:

  • 获取特定目录中所有Excel文件的集合
  • 迭代遍历每个文件中的每个工作表,并将其导出为 .csv 文件

目前,这是每个文件的六步过程:

--how to create CSV files for all worksheets in a file:
1. open file
2. click "Developer"
3. click editor
4. click ThisWorkbook
5. copy in:
Sub save_all_csv()
    On Error Resume Next
    Dim ExcelFileName As String
    ExcelFileName = ThisWorkbook.Name
    For Each objWorksheet In ThisWorkbook.Worksheets
        Filename = "FILE-" & ExcelFileName & "-WORKSHEET-" & objWorksheet.Name & ".csv"
        objWorksheet.SaveAs Filename:="Macintosh HD:Users:edward:Documents:temporaryNoBackup:" & Filename, FileFormat:=xlCSV, CreateBackup:=False
    Next
    Application.DisplayAlerts = False
    Application.Quit
End Sub
6. click run (it closes by itself)

我正在寻找一种在Mac上自动化的方法,理想情况下,一个(cron job?,service?)会每隔10分钟打开一个excel文件,这样就会查看一个目录,将所有其他Excel文件转换为.csv文件,然后自行关闭。

如果没有Scripting.FileSystemObject,如何在Mac上完全自动进行Excel到CSV转换?

2 个答案:

答案 0 :(得分:1)

我能想到的唯一方法就是使用“Dir”功能。由于mac支持其文件名中的额外字符,因此通配符不适用于“Dir”函数。这是一个样本。

Function GetFileList(folderPath As String) As Collection
'mac vba does not support wildcards in DIR function

    Dim file As String
    Dim returnCollection As New Collection

    If Right$(folderPath, 1) <> "/" Then
        folderPath = folderPath & "/"
    End If

    file = Dir$(folderPath) 'setup initial file

    Do While Len(file)
        returnCollection.Add folderPath & file
        file = Dir$
    Loop

    Set GetFileList = returnCollection
End Function

答案 1 :(得分:0)

您可以将 VBA 放在附加到 Excel 本身的加载项(.xlam 文件)中,而不是放在工作簿中。对于您的示例代码,唯一的修改是针对 ActiveWorkbook 而不是 ThisWorkbook

Sub save_all_csv()
    On Error Resume Next
    Dim ExcelFileName As String
    ExcelFileName = ActiveWorkbook.Name
    For Each objWorksheet In ActiveWorkbook.Worksheets
        Filename = "FILE-" & ExcelFileName & "-WORKSHEET-" & objWorksheet.Name & ".csv"
        objWorksheet.SaveAs Filename:="Macintosh HD:Users:edward:Documents:temporaryNoBackup:" & Filename, FileFormat:=xlCSV, CreateBackup:=False
    Next
    Application.DisplayAlerts = False
    Application.Quit
End Sub

您还可以利用 auto_open() 自动绑定热键。完成后,您只需打开工作簿,按热键即可获取 CSV 文件。

Public Sub auto_open()

'   Register hotkeys

'   See key codes here
'   https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-onkey-method-excel

'   ^ = CTRL
'   % = ALT
'   + = SHIFT

    Application.OnKey "^+e", "save_all_csv" ' Ctrl+Shift+E will call save_all_csv()

End Sub