Friday, February 20, 2015

VBA Script to Search Google for Selected Text in Any Word Version

Though there is a way to tweak Word 2013 to turn the "Search with Bing" context menu option into "Search with Google", neither can be found in Word 2007. So, I wrote a little VBA script to make searching Google from Word's selected text just a keyboard shortcut or mouse click away.

To add this to your Word installation, enable the Developer tab under the advanced options (it's actually under Popular in Word 2007). On it, click Macros. Pull down "Macros in" and choose "Normal.dotm (global template)". Type "SearchGoogle" or any name without spaces into the "Macro name" textbox and click Create. The VBA Editor appears. Paste the following code into it:

Private Declare Function ShellExecute _
 Lib "shell32.dll" Alias "ShellExecuteA" ( _
 ByVal hWnd As Long, _
 ByVal Operation As String, _
 ByVal Filename As String, _
 Optional ByVal Parameters As String, _
 Optional ByVal Directory As String, _
 Optional ByVal WindowStyle As Long = vbMaximizedFocus _
) As Long
Sub SearchGoogle()
 Dim text As String
 text = Selection.text
 text = Replace(text, " ", "%20")
 Dim res As Long
 res = ShellExecute(0, "Open", "http://google.com/search?q=" & text)
End Sub

Click the Save button in the VBA Editor, then close it. Now decide whether you want a keyboard shortcut or a Quick Access Toolbar button for the macro.

If you want a keyboard shortcut, open the options and find the place to configure keyboard shortcuts. (On Word 2007, the button is on the Customize tab. On Word 2013, it can be found at the bottom of the page on the "Customize Ribbon" tab.) Choose Macros from the left list, then the macro you just created on the right. Click on the "Press new shortcut key" box and press the shortcut key you want for this. Save your changes and exit all dialog boxes.

If you want a mouse-accessible button, find the place to customize the Quick Access Toolbar under Word Options. Pull down "Choose commands from" and choose Macros. Select the macro, then click "Add >>" to move it onto the QAT. You can then modify its icon and mouseover text if you'd like, with the Modify button.

You can now use either a keyboard shortcut or a QAT button to search Google for your selected text.

3 comments:

  1. Hi Fleex, I tried to add this macro to my Word in VBA but I can't make it work. I have a feeling I am missing something. Anyway, would you be able to provide a word file containing this macro? Many thanks, this would be great to use once I have it installed. Cheers, Renata

    ReplyDelete
    Replies
    1. No problem, here you go: https://dl.dropboxusercontent.com/u/3771470/SearchGoogle.dotm

      I hope that helps.

      Delete