Input box VBA code

ftsang

New Member
Joined
Jun 9, 2005
Messages
25
Hi Guys,
I am looking for some VBA code which brings up an input box for the user to fill in, which asks a simple yes/no question, such as "Do you own a car?"

Then, I want it to give an error message if the input is not "Yes" or "No".

And ideas?

Thanks!
 

Some videos you may like

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.

BrianB

Well-known Member
Joined
Feb 17, 2003
Messages
8,127
Best to not allow any alternative. Try this :-
Code:
Sub test()
    rsp = MsgBox("Do you own a car ", vbYesNo)
    If rsp = vbYes Then
        answer = " Yes"
    Else
        answer = "No"
    End If
End Sub
 

Von Pookie

MrExcel MVP
Joined
Feb 17, 2002
Messages
13,686
If you're just going to use a yes/no question, a simple msgbox would be easier. Then they would only have yes/no options--no chance to enter anything else.

Msgbox "Do you own a car?",vbyesno
 

Cbrine

Well-known Member
Joined
Dec 2, 2003
Messages
3,196
Code:
Sub Question()
Dim Response As String, AnsweredCorrectly As Boolean

AnsweredCorrectly = False

Do Until AnsweredCorrectly = True
        Response = InputBox("Do you own a car?")
        Select Case Response
        Case "Yes"
            MsgBox "you do own a car"
            AnsweredCorrectly = True
        Case "No"
            MsgBox "You don't own a car"
            AnsweredCorrectly = True
        Case Else
            MsgBox "You didn't respond correctly"
            
        End Select
Loop

ENd sub

HTH
Cal
 

Andrew Poulsom

MrExcel MVP
Joined
Jul 21, 2002
Messages
73,092

ADVERTISEMENT

You can use the MsgBox function like this:

Code:
Sub Test()
    Dim Ans As Variant
    Ans = MsgBox("Do you own a car?", vbQuestion + vbYesNo, "Car Owner")
    If Ans = vbYes Then
'       code for car owner
    Else
'       code for non car owner
    End If
End Sub
 

ftsang

New Member
Joined
Jun 9, 2005
Messages
25
VBA input Box Code

Unfortunately I am still stuck.
The method mentioned by Cbrine works the best, but it doesn't let me drop out of the loop if the cancel button is pressed. Help!
 

Cbrine

Well-known Member
Joined
Dec 2, 2003
Messages
3,196
Code:
Sub Question()
Dim Response As String, AnsweredCorrectly As Boolean
AnsweredCorrectly = False

Do Until AnsweredCorrectly = True
        Response = InputBox("Do you own a car?")
        Select Case Response
        Case ""
            Exit Do
        Case "Yes"
            MsgBox "you do own a car"
            AnsweredCorrectly = True
        Case "No"
            MsgBox "You don't own a car"
            AnsweredCorrectly = True
        Case Else
            MsgBox "You didn't respond correctly"
            
        End Select
Loop

End Sub

HTH
Cal
 

Watch MrExcel Video

Forum statistics

Threads
1,118,909
Messages
5,574,985
Members
412,630
Latest member
Eireangel
Top