从Mac上的VBA Macro启动Google搜索

问题描述 投票:3回答:1

就在前面,我不是一个真正的程序员。我从事编辑工作,我们公司使用许多宏来简化我们的流程和功能(很多findReplace,识别不一致的拼写/间距约定等)。话虽这么说,我已经开始了解VBA编辑器如何在Microsoft Word上运行。

我们有一个Fetch宏(最初由Paul Beverley创建),它对所有使用PC的员工都非常有效。它采用文档中突出显示的术语,自动打开Web浏览器,并执行谷歌搜索。但是,我们有几名员工使用Office for Mac 2011,他们无法使用与PC用户相同的功能。我真的很想调整它以便它可以在Mac上运行,但我缺乏训练严重妨碍了我。

这是我们公司用于PC的原始脚本:

Sub GoogleFetch()
' Version 08.05.12
' Launch selected text on Google

useExplorer = False

runBrowser = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

mySite = "http://www.google.com/#q="

If Len(Selection) = 1 Then Selection.Words(1).Select
mySubject = Trim(Selection)
mySubject = Replace(mySubject, "&", "%26")
mySubject = Replace(mySubject, " ", "+")

If useExplorer = True Then
  Set objIE = CreateObject("InternetExplorer.application")
  objIE.Visible = True
  objIE.navigate mySite & mySubject
  Set objIE = Nothing
Else
  Shell (runBrowser & " " & mySite & mySubject) 'ERROR HERE
End If
End Sub

(我可能会删除useExplorer函数。)

我已经尝试使用Macscript和OpenURL来解决runBrowser问题(错误弹出Shell ...行,因为我无法正确路径),但它引起了更多的麻烦。

是否有一些简单的修复方法,我想要解决这个问题?在此先感谢您的帮助!

excel vba macos excel-vba excel-vba-mac
1个回答
2
投票

您可以使用#If ... #End If以不同方式处理这两个系统(Mac和PC),请注意开头的#。这将在编译时运行,并且取决于系统,只留下在运行时执行的合适代码。

你可以很容易地使用MacScript来打开Safari:http://www.officeonemac.com/vba/open_url.html

所以你的代码看起来像这样:

Sub GoogleFetch()
    ' Version 08.05.12
    ' Launch selected text on Google

    runBrowser = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    mysite = "http://www.google.com/#q="

    If Len(Selection) = 1 Then Selection.Words(1).Select
    mysubject = Trim(Selection)
    mysubject = Replace(mysubject, "&", "%26")
    mysubject = Replace(mysubject, " ", "+")

    #If Mac Then
        OpenURL mysite & mysubject
    #Else
        Shell runBrowser & " " & mysite & mysubject
    #End If
End Sub

Private Sub OpenURL(ByVal URL As String)
    Dim s As String
    s = "tell application ""Safari""" + vbCrLf + _
        "open location """ + URL + """" + vbCrLf + _
        "end tell"
    MacScript s
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.