In lesson 8, you have understood different types of data and learned how to write code involving the numeric and non-numeric data. In this lesson, you shall learn how to store the data and how to declare them. In Visual Basic 2019, data can be stored as variables or constants. Variables are like mailboxes in the post office. The content of the variable changes every now and then, just like the mailboxes. In Visual Basic 2019, variables are the specific areas allocated by the computer memory to store data.
Like the mailboxes, you must assign a name to the variable. To name a variable in VB2019, you have to follow a set of rules as follows:
Some examples of valid and invalid variable names are displayed in Table 9.1
|Valid Names||Invalid Name|
|Long_Name_Can_beUSE||LongName&Canbe&Use *& is not acceptable|
In Visual Basic 2019, you need to declare the variables before you can use them. To declare a variable, you assign a name to the variable and state its data type. If you fail to do so, the program will run into an error. Variables are usually declared in the general section of the code windows using the Dim statement.
The syntax to declare a variable in VB 2019 is as follows:
Dim VariableName As DataType
If you want to declare more variables, you can declare them in separate lines or you may also combine them in one line, separating each variable with a comma, as follows:
Dim VariableName1 As DataType1 Dim VariableName2 As DataType2 Dim VariableName3 As DataType3
Dim VariableName1 As DataType1, VariableName2 As DataType2, VariableName3 As DataType3
This example declares two variables of the string type and concatenates them using the ampersand sign &. Create a project and insert a Button and name ii as BtnShow and change its text to Show Message. You can assign a value to the string using the = sign. Now enter the following code:
Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles BtnShow.Click Dim YourName As String = " George" Dim MyMsg As String MyMsg = "Happy Birthday!" MsgBox(MyMsg & YourName) End Sub
Running the code and clicking the show message button produces the following message:
In this example, we create a simple calculator where the user enter his name, two numbers and click the Calculate button to compute the addition of the two numbers. It also display the date. There are three data types here, String, Integer and Date. We also use the Format function to display the current date of computation.
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click Dim YourName As String Dim Num1 As Integer Dim Num2 As Single Dim Sum As Integer Dim RunDate As Date YourName = TxtName.Text Num1 = Val(TxtNum1.Text) Num2 = Val(TxtNum2.Text) Sum = Num1 + Num2 LblSum.Text = Str(Sum) RunDate = Format(Now, "General Date") LblDate.Text = RunDate End Sub
Running the program and clicking on the Calculate button produces the following output as shown in Figure 9.2.
After declaring various variables using the Dim statements, we can assign values to those variables. The syntax of an assignment in Visual Basic 2019 is
*You may also declare a variable by assigning an initial value to it, as shown in the following examples:
Dim VarName as String="ABC" Dim VarNum as Interger=100
The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more, as illustrated in the following examples:
firstNumber=100 secondNumber=firstNumber-99 userName=”John Lyan” userpass.Text = password Label1.Visible = True Command1.Visible = false Label4.text = textbox1.Text ThirdNumber = Val(usernum1.Text) total = firstNumber + secondNumber+ThirdNumber MeanScore% = SumScores% / NumSubjects% X=sqr (16) TrimString= Ltrim (“ Visual Basic”, 4) Num=Int(Rnd*6)+1
An error occurs when you try to assign a value to a variable of incompatible data type. For example, if you have declared a variable as an integer but you assigned a string value to it, an error occurred, as shown in Example 9.3:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim YourMessage As Integer YourMessage = "Happy Birthday!" MsgBox(YourMessage) End Sub
When you run the program, the following error messages will appear in a dialog box, as shown in Figure 9.3
In Visual Basic 2019, we usually use the Dim keyword to declare the data. However, you can also use other keywords to declare the data. Three other keywords are private, static and public. The forms are as shown below:
Private VariableName as Datatype Static VariableName as Datatype Public VariableName as Datatype
The above keywords indicate the scope of the declaration. Private declares a local variable or a variable that is local to a procedure or module. However, Private is rarely used, we normally use Dim to declare a local variable. The Static keyword declares a variable that is being used multiple times, even after a procedure has been terminated. Most variables created inside a procedure are discarded by Visual Basic when the procedure is terminated. Static keyword preserves the value of a variable even after the procedure is terminated. Public is the keyword that declares a global variable, which means it can be used by all the procedures and modules of the whole VB2019 program.
Constants are different from variables in the sense that their values do not change during the running of the program.The syntax to declare a constant in is
Const Constant Name As Data Type = Value
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Const Pi As Single = 3.142 Dim R As Single = 10 Dim AreaCircle As Single AreaCircle = Pi * R ^ 2 MsgBox("Area of circle with " & "radius" & R & "=" & AreaCircle) End Sub
Press F5 to run the program and clicking the button will produce the following message: