首页 > 解决方案 > VBA - 在 Mac 上打开文件夹

问题描述

我只是想通过 VBA 打开一个文件夹。我已经尝试了以下代码,但它什么也没做。

对于 Windows,我知道以下命令可以正常工作

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

这是我正在使用的代码...

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 

您能帮我获取在 Mac 上简单地打开文件夹的代码吗?谢谢!

标签: vbamacosapplescript

解决方案


AppleScript 通过告诉特定应用程序执行应用程序开发人员提供的脚本字典(如果有)中公开的一个或多个命令来完成这些类型的事情。对于Finder(始终运行),它将是:

tell application "Finder" to open theFolder

其中theFolder是一个aliasfilePOSIX file对象,例如来自:

set theFolder to (choose folder)

请注意,openshell 实用程序通常用于打开文件和应用程序。


未经测试的例子:

较旧(已弃用)的样式:

• 请注意,此命令可能不适用于沙盒应用程序。

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)

较新的(2016+)风格:

• 使用包含您要调用的处理程序(子例程)的脚本编辑器创建一个脚本,例如:

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

• 将脚本放在用户的~/Library/Application Scripts/[bundle id]文件夹中,其中[bundle id] 是使用该脚本的应用程序的捆绑标识符。

• 新命令的格式AppleScriptTask("script file name.scpt", "handler name", "handler argument")为 ,例如:

Dim FolderPath as String

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

请参阅使用 VB 运行 AppleScript


推荐阅读