Here is code to present the user with a Yes/No Message box and have the ability to run code based on the response.
It works by setting a variable equal to the message box response and evaluating the variable with an IF…THEN statement.
The code is commented in locations for changing the message text displayed, where to place code for a Yes response, and No response.
To retrieve a user inputted string, see my post about the InputBox.
Sub YesNoMessageBox()
Dim Answer As String
Dim MyNote As String
'Place your text here
MyNote = "Do you agree?"
'Display MessageBox
Answer = MsgBox(MyNote, vbQuestion + vbYesNo, "???")
If Answer = vbNo Then
'Code for No button Press
MsgBox "You pressed NO!"
Else
'Code for Yes button Press
MsgBox "You pressed Yes!"
End If
End Sub
February 6th, 2005 at 6:19 pm
First thing I saw on the graphic above was three question marks, and immediately related that to using non-Roman fonts (as I deal with Korean users/operating systems/file names/dialog boxes on a daily basis).
Recommend you spell out the question in the MsgBox - at least for the title. I’ve screwed up more than once by agreeing to something I shouldn’t have.
(I realize that this is a quick demonstration of if…then and not language incompatabilities.)
February 7th, 2005 at 11:28 am
I use the PRE tag for my code, unfortunately it doesn’t automatically wrap without some CSS which I don’t use.
I had the message written out but shortened it so it didn’t move my margins into my navigation. However,
I didn’t give any thought to mutltiple languages and the need to always spell out the message box titles, thanks for the heads up.
August 5th, 2008 at 4:45 am
Thanks for the useful example! I knew I wanted something like this, but I couldn’t find anything similar in the help files. This yes/no msgbox was exactly what I needed.
August 15th, 2008 at 4:55 am
Private Sub Modify_Click()
x = MsgBox(”Are you sure you want to modify records?”, vbYesNo, “SLSA Engineering Database”)
DoCmd.OpenForm “Modify Record Menu”, acNormal
End Sub
…..i have this code but evertime i click No buttong in the message box it still open me a form… please help me if there is still missing in my codes and what was it?…Im not a programmer, anyone can help with this code?
September 15th, 2008 at 9:18 pm
I would assume that you need an if/then/else loop based on x, otherwise it will hit your second line every time.
November 10th, 2008 at 7:47 pm
Sub MsgBox4()
MsgBox title:=”Analysis of Acctg Activities”, Prompt:=”Can not execute your command. No data availabe for that period.”
End Sub
When run this code it jumps to the conclusion. “Wrong number of orgumaents or invalid property assignment” and shows the MsgBox. I ran this code before several times without any problem. Now I am using Excel 2007.