Solved Exercise
Exercise Solution
-
First we will create the layout of the UserForm with three buttons, starting with the "Stop the vote" button.
It starts with "Stop the vote" first so that VBA does not give the initial Focus to the button of one of the candidates.
-
We change the TakeFocusOnClick property of the buttons to False, so that we do not influence the next voter.
Try to run without these properties at the end of the exercise.
-
Double-click the buttons to create your Sub of event _Click and declare the variables for counting votes outside the scope of these subroutines.
Dim voteA As Integer
Dim voteB As Integer
Private Sub CommandButton2_Click()
End Sub
Private Sub CommandButton3_Click()
End Sub
Private Sub CommandButton1_Click()
End Sub
-
Create a MsgBox that tells you when votes are counted and counts them when you click the button to end the poll, showing who won (or if there was a tie) and clearing scores:
Dim voteA As Integer
Dim voteB As Integer
Private Sub CommandButton2_Click()
voteA = voteA + 1
MsgBox "Thanks for your vote!"
End Sub
Private Sub CommandButton3_Click()
voteB = voteB + 1
MsgBox "Thanks for your vote!"
End Sub
Private Sub CommandButton1_Click()
If voteA > voteB Then
MsgBox "Candidate A has won!"
ElseIf voteA < votacaoB Then
MsgBox "Candidate B has won!"
Else
MsgBox "Voting equaled."
End If
voteA = 0
voteB = 0
End Sub
Consolidated answer
Dim voteA As Integer
Dim voteB As Integer
Private Sub CommandButton2_Click()
voteA = voteA + 1
MsgBox "Thanks for your vote!"
End Sub
Private Sub CommandButton3_Click()
voteB = voteB + 1
MsgBox "Thanks for your vote!"
End Sub
Private Sub CommandButton1_Click()
If voteA > voteB Then
MsgBox "Candidate A has won!"
ElseIf voteA < votacaoB Then
MsgBox "Candidate B has won!"
Else
MsgBox "Voting equaled."
End If
voteA = 0
voteB = 0
End Sub
SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.
Excel ® is a registered trademark of the Microsoft Corporation.
© 2024 SuperExcelVBA | ABOUT