0

I have found the Macro for MS Word (as below) from the website https://excelchamps.com/blog/vba-code-search-google-chrome/

Sub GoogleSearch()

Dim chromePath As String
Dim search_string As String
Dim query As String

query = InputBox("Please enter the keywords", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")

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

Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & search_string)

End Sub

I would like to close the Message Box when I mistakenly press the Macro button/ran this Macro. However, whatever I press (Yes/No/Close that msgbox), it ignored all of these choices and automatically search what I type in the msgbox.

I tried to add the below code but it doesn't work.

If MsgBoxResult = vbCancel Then
    Exit Sub
    Else

I am junior to Word Macro. May I ask if anyone have any suggestions to make the msgbox work? (press cancel or close the window and then don't open Chrome and search automatically) Thank you for your kind attention.

macropod
  • 12,757
  • 2
  • 9
  • 21
7hcl5
  • 5
  • 2
  • 2
    Maybe [this answer](https://stackoverflow.com/a/16063938/12287457) is what you are looking for. – GWD Oct 18 '22 at 07:32
  • 1
    There is no Message Box in your GoogleSearch sub - only an Input Box. The two are entirely different. – macropod Oct 18 '22 at 07:34

1 Answers1

1

Just have a look to the official documentation for InputBox

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box.

(...)

If the user chooses OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user chooses Cancel, the function returns a zero-length string ("").

So (in opposite to MsgBox), the InputBox always returns a String, while vbCancel is a number. You will need to check if the return value is the empty string. Note that you can't distinguish between "the user didn't enter something and pressed [OK]" or "the user pressed [Cancel]".

If MsgBoxResult = "" Then Exit Sub
FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • 1
    According to [this answer](https://stackoverflow.com/a/16063938/12287457) it is possible to distinguish between "the user didn't enter something and pressed [OK]" or "the user pressed [Cancel]". – GWD Oct 18 '22 at 07:35
  • @FunThomas May I know which row I should put this code "If MsgBoxResult = "" Then Exit Sub" since the macro failed after adding this code. How to add code to make the macro search google when typed keywords in Inputbox and exit sub when inputbox is empty. – 7hcl5 Oct 18 '22 at 12:16
  • Exactly as you have it now. I just changes the line to a one-line If statement as you don't need an `else`. With other words, put it immediately after the lnputBox-statement. – FunThomas Oct 18 '22 at 12:26