Tag Archives: VB

Visual Basic Selection Using IF

Programs need to be able to branch and execute different instructions for different conditions. We can do this most simply using the IF statement.

We wanted to modify yesterday’s program so that we could turn it into a game. The user needs to guess the number that has been created by the dice roll. They have only one shot to get it right.

Some programmers noticed that the number the same the first few times they tried it, why do you think it was?

Continue reading Visual Basic Selection Using IF

VB Program for Displaying the Average of 20 Marks

Below is the program from today’s lesson. It is not completed, I would like you to Change the program to display the average with two decimal places. Please add your solution with a comment below.

Private Sub CmdStart_Click()
'load an Array with data from a list box
'list box is hidden on the form
'List Boxes count from 0 so add a heading to the fist item
Dim IntNumber(20) As Integer
Dim StrName(20) As String
Dim intavg As Integer
Call Load_Array(IntNumber(), StrName())
Call Calc_Average(IntNumber(), intavg)
Call Display_Array(IntNumber(), StrName(), intavg)
End Sub

Private Sub Load_Array(ByRef Number() As Integer, ByRef StrName() As String)
Dim Counter As Integer 'local Variable
For Counter = 1 To 20
Number(Counter) = LstNumbers.List(Counter)
StrName(Counter) = LstNames.List(Counter)
Next
End Sub


Private Sub Calc_Average(ByRef IntNumber() As Integer, ByRef intavg As Integer)
Dim IntSum As Integer
For Counter = 1 To 20
IntSum = IntSum + IntNumber(Counter)
Next
intavg = IntSum / 20
End Sub

Private Sub Display_Array(ByRef Number() As Integer, ByRef StrName() As String, ByVal intavg)
'Standard procedure as used in previous programs
Dim Counter As Integer 'local Variable
For Counter = 1 To 20
Form1.Print StrName(Counter) & " scored " & Number(Counter) & "%"
Next
Form1.Print "Average = " & intavg & "%"
End Sub

Code for Corrie

Option Explicit

Private Sub Command1_Click()
‘Set up variables
Dim NumA As Single
Dim NumB As Single

Call Get2Numbers(NumA, NumB)
Call DisplaySum(NumA, NumB)

End Sub

Sub Get2Numbers(ByRef NumA, ByRef NumB)
NumA = InputBox(“What is the first number”)
NumB = InputBox(“What is the second number”)
End Sub

Sub DisplaySum(ByVal NumA, ByVal NumB)
MsgBox (NumA + NumB)
End Sub