Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MsgBox Yes/No Excel VBA

Tags:

excel

vba

msgbox

I have a Yes/No MsgBoxin my VBA script that returns a question for the user to answer. Whenever the "Yes" or "No" buttons are pressed, besides the script running its respective code, another MsgBox with the numbers "6" or "7" pops up. How do I disable this second MsgBox?

Here's my code:

Dim question As Integer
question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you like to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")

MsgBox question

If question = vbYes Then
    Sheets("Results").Range("D6").ClearContents
    Sheets("Results").Range("D7").ClearContents
    Category = Sheets("Results").Range("D6").Value
Else
    Sheets("Results").Range("D5").ClearContents
    Sheets("Results").Range("D6").ClearContents
    Sheets("Results").Range("D7").ClearContents
    Exit Sub
End If
like image 449
franciscofcosta Avatar asked Nov 24 '16 16:11

franciscofcosta


People also ask

How do I create a yes no box in Excel VBA?

In VBA, using the message box we can create a yes no msgbox which is used to record user input based on the click on yes or no, the syntax to make a yes no message box is as follows variable = MsgBox(“Text”, vbQuestion + vbYesNo + vbDefaultButton2, “Message Box Title”) where variable must be declared as an integer.

How do I break a line in a Messagebox in VBA?

CHR (10) is the code to insert a new line in VBA.


1 Answers

The MsgBox function returns a vbMsgBoxResult value, which is an enum (and should be a Long integer, not an Integer).

You're calling it twice:

Dim question As Integer
question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you like to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")

MsgBox question

Once to assign question, and once to display question - which at that point is going to contain either vbYes (6) or vbNo (7).

enter image description here

I would declare question As vbMsgBoxResult to avoid ambiguities and get autocomplete/IntelliSense when you later use it. Actually, result or answer would be a better identifier - "question" sounds like the question itself, not the user's response.

like image 117
Mathieu Guindon Avatar answered Oct 19 '22 19:10

Mathieu Guindon