【问题标题】:Launch a Google search from VBA Macro on Mac在 Mac 上从 VBA 宏启动 Google 搜索
【发布时间】:2020-07-01 14:53:38
【问题描述】:

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

我们有一个 Fetch 宏(最初由 Paul Beverley 创建),它非常适合所有使用 PC 的员工。它采用文档中突出显示的术语,自动打开网络浏览器,并执行谷歌搜索。但是,我们有几名员工使用 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


    【解决方案1】:

    您可以使用#If ... #End If 区别对待这两个系统(Mac 和PC),注意开头的#。这将在 compile 时间运行,根据系统,只留下合适的代码在 run 时间执行。

    您可以使用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
    

    【讨论】:

    • 谢谢,我试试看!我能否使用 OpenURL 命令将浏览器从 Safari 更改为 Chrome 或 Firefox?
    • @felicityrose 是的,只需将 Safari 的位置更改为 Chrome :) 如果您觉得这很有用,请点赞,如果它解决了您的问题,请将其标记为已接受(左侧的灰色刻度线)。谢谢!
    • 没问题,乐于助人!
    • 嗨@CallumDA,我们是否需要添加任何额外的东西来使用该MacScript命令打开浏览器,就像mac机器中的任何dll一样,它将如何在内部使用该MacScript代码
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多