简体   繁体   中英

VBA - Open a folder on Mac

I simply want to open a folder by VBA. I've tried the following code but it does nothing.

For Windows I know the following command is working fine

Call Shell("explorer.exe " & filepath, vbNormalFocus)

This is the code I am using...

Sub Open_Folder_On_Mac()
Dim folderPath As String
Dim RootFolder As String
Dim scriptstr As String

On Error Resume Next
RootFolder = MacScript("return (path to desktop folder) as String")

scriptstr = "do shell script ""open " & RootFolder & """"

MacScript (scriptstr)
End Sub 

Can you help me, getting the code for simply opening a folder on a Mac? Thanks!

AppleScript does these kinds of things by telling a particular application to perform one or more of the commands exposed in the scripting dictionary (if any) provided by the application developer. In the case of the Finder (which runs at all times), It would be:

tell application "Finder" to open theFolder

where theFolder is an alias , file , or POSIX file object, for example from:

set theFolder to (choose folder)

Note that the open shell utility is normally used to open files and applications.


Untested examples:

The older (deprecated) style:

• Note that this command may not work in a sandboxed application.

Dim ScriptString as String
Dim FolderPath as String

ScriptString = "tell application " & Chr(34) & "Finder" &  Chr(34) & " to open folder (path to desktop)"
-- or --
FolderPath = "Macintosh HD:Users:you:Path:To:Some:Folder:"
ScriptString =  "tell application " & Chr(34) & "Finder" &  Chr(34) & " to open folder " & FolderPath

MacScript(ScriptString)

The newer (2016+) style:

• Create a script using the Script Editor that contains the handlers (subroutines) you want to call, for example:

on openFolder(folderPath)
    tell application "Finder" to open folder folderPath
end openFolder

• Place the script in your user's ~/Library/Application Scripts/[bundle id] folder, where [bundle id] is the bundle identifier of the application using the script.

• The new command is in the form AppleScriptTask("script file name.scpt", "handler name", "handler argument") , for example:

Dim FolderPath as String

FolderPath = "Macintosh HD:Users:you:Path:To:Some:Folder:"
AppleScriptTask("MyScript.scpt", "openFolder", FolderPath)

See Run an AppleScript with VB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM