Share via

Command button to display combobox contents

Anonymous
2017-02-16T01:06:44+00:00

I have a combobox in a form, I want to enter text in the combobox and click the command button.  If the string “Red” is in the combobox then I want the msgbox "This is Red", if the string “Green” is in the combobox then I want msgbox "This is Green", and if the string “Blue” is in the combobox I want the msgbox "This is Blue".  Can you help?

Private Sub CommandButton5_Click()

If ComboBox5.Text = “Red” then

msgbox "This is Red"

ElseIf ComboBox5.text = “Green” then

msgbox "This is Green"

Else ComboBox5.text = “Blue” then

msgbox "This is Blue"

End If

End Sub

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2017-02-21T12:10:24+00:00

Try this:

Private Sub CommandButton5_Click()

    Select Case ComboBox5.Text

        Case "Red"

            MsgBox "This is " & ComboBox5.Text

        Case "Blue"

            MsgBox "This is " & ComboBox5.Text

        Case "Green"

            MsgBox "This is " & ComboBox5.Text

        Case "Yellow"

            MsgBox "This is " & ComboBox5.Text

    End Select

End Sub

Was this answer helpful?

0 comments No comments

Answer accepted by question author

Andreas Killer 144.1K Reputation points Volunteer Moderator
2017-02-16T08:03:41+00:00

Private Sub CommandButton5_Click()

  MsgBox "This is " & ComboBox5.Text

End Sub

Too simple?

Andreas.

Was this answer helpful?

0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2017-02-21T14:05:24+00:00

    The only issue I see with the original code you posted is:

    Else ComboBox5.text = “Blue” then

    That line should not use Else but ElseIf.  ElseIf is used to list another condition (no matter how many).  Else is not followed by a condition, and also not by "Then".  It covers situations where none of the above If/ElseIf are not met, and is not required in your case.

    If ... then

    something happens

    Elseif ... then

    something else happens

    Elseif ... then

    yet another option

    Else

    if none of the above were true then this happens

    End If

    Cimjet's Select Case option is another nice way to do it.

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2017-02-21T02:44:32+00:00

    That works but can you show me how to make it work with the code I posted?

    Was this answer helpful?

    0 comments No comments