FileDialog in Word 2011 VBA

给你一囗甜甜゛ 提交于 2019-12-04 14:55:23

I believe you have to use Apple Script in order to do this a bit better on the Mac. The following code allows the user to select text files which is returned as an array from the function. You would simply be able to modify the Apple Script to return other file types and select directories, I'll leave that to you.

The code that calls the function and displays a message box with all the files:

Sub GetTextFilesOnMac()
    Dim vFileName As Variant

    'Call the function to return the files
    vFileName = Select_File_Or_Files_Mac

    'If it's empty then the user cancelled
    If IsEmpty(vFileName) Then Exit Sub

    'Loop through all the files specified
    For ii = LBound(vFileName) To UBound(vFileName)
        MsgBox vFileName(ii)
    Next ii

End Sub

And the function that does the Apple Script work:

Function Select_File_Or_Files_Mac() As Variant
    'Uses AppleScript to select files on a Mac
    Dim MyPath As String, MyScript As String, MyFiles As String, MySplit As Variant

    'Get the documents folder as a default
    On Error Resume Next
    MyPath = MacScript("return (path to documents folder) as String")

    'Set up the Apple Script to look for text files
    MyScript = "set applescript's text item delimiters to "","" " & vbNewLine & _
            "set theFiles to (choose file of type " & " {""public.TEXT""} " & _
            "with prompt ""Please select a file or files"" default location alias """ & _
            MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
            "set applescript's text item delimiters to """" " & vbNewLine & _
            "return theFiles"

    'Run the Apple Script
    MyFiles = MacScript(MyScript)
    On Error GoTo 0

    'If there are multiple files, split it into an array and return the results
    If MyFiles <> "" Then
        MySplit = Split(MyFiles, ",")
        Select_File_Or_Files_Mac = MySplit
    End If
End Function

Finally, it can be a bit of a pain specifying different file types, if you want to specify only Word documents, then replace public.TEXT with com.microsoft.word.doc, however this won't allow .docx or .docm files. You need to use org.openxmlformats.wordprocessingml.document and org.openxmlformats.wordprocessingml.document.macroenabled respectively for these. For more info on these see: https://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!