Lesson 9: Variables and Constants in VB2019

Master data storage and management for robust application development

Key Takeaway

Variables and constants are essential for storing and managing data in your applications. Understanding their declaration, scope, and usage is fundamental to effective Visual Basic programming.

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 specific areas allocated by computer memory to store data. Constants are different from variables in that their values do not change during program execution.

9.1 Variable Names

To name a variable in VB2019, you must follow these rules:

1 Character Limit

Must be less than 255 characters

2 No Spaces

Spaces are not allowed

3 Start with Letter

Cannot begin with a number

4 No Periods

Periods are not permitted

Table 9.1: Valid and Invalid Variable Names
Valid Names Invalid Names
My_Name My.Name (period not allowed)
vb2019 2019vb (cannot start with number)
Long_Name_Can_beUSE LongName&Canbe&Use (ampersand not acceptable)

9.2 Declaring Variables

In Visual Basic 2019, you need to declare variables before you can use them. Variables are usually declared in the general section of the code windows using the Dim statement.

Declaration Syntax

The syntax to declare a variable in VB2019 is:

Dim VariableName As DataType

For multiple variables:

Dim VariableName1 As DataType1
Dim VariableName2 As DataType2
Dim VariableName3 As DataType3

Or in a single line:

Dim VariableName1 As DataType1, VariableName2 As DataType2, VariableName3 As DataType3

Example 9.1: Simple Variable Declaration

This example declares two string variables and concatenates them using the ampersand sign &.

Form1.vb
Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles BtnShow.Click
    ' Declare and initialize a string variable
    Dim YourName As String = " George"
    
    ' Declare a string variable and assign value later
    Dim MyMsg As String
    MyMsg = "Happy Birthday!"
    
    ' Display concatenated message
    MsgBox(MyMsg & YourName)
End Sub

Output:

> Result: "Happy Birthday! George"
Message box output
Figure 9.1: Message box output

Example 9.2: Simple Calculator

In this example, we create a simple calculator that takes user input, performs addition, and displays the current date.

Form1.vb
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
    ' Declare variables with different data types
    Dim YourName As String
    Dim Num1 As Integer
    Dim Num2 As Single
    Dim Sum As Integer
    Dim RunDate As Date
    
    ' Assign values from form controls
    YourName = TxtName.Text
    Num1 = Val(TxtNum1.Text)
    Num2 = Val(TxtNum2.Text)
    
    ' Perform calculation
    Sum = Num1 + Num2
    
    ' Display results
    LblSum.Text = Str(Sum)
    
    ' Format and display date
    RunDate = Format(Now, "General Date")
    LblDate.Text = RunDate
End Sub
Calculator interface
Figure 9.2: Calculator interface

9.3 Assigning Values to Variables

After declaring variables, we can assign values using the assignment operator (=). The syntax is:

Variable = Expression

You can also declare and initialize a variable in one line:

Dim VarName As String = "ABC"
Dim VarNum As Integer = 100

Examples of valid assignments:

firstNumber = 100
secondNumber = firstNumber - 99
userName = "John Lyan"
Label1.Visible = True
Command1.Visible = False
Label4.text = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber + ThirdNumber

Example 9.3: Type Mismatch Error

An error occurs when you try to assign a value to a variable of an incompatible data type.

Form1.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Declare an integer variable
    Dim YourMessage As Integer
    
    ' Attempt to assign a string to an integer variable
    YourMessage = "Happy Birthday!"
    
    MsgBox(YourMessage)
End Sub

Output:

> Error: Conversion from string "Happy Birthday!" to type 'Integer' is not valid.
Type mismatch error
Figure 9.3: Type mismatch error

Best Practice

Always declare variables with the appropriate data type for the values they will hold. Use Option Strict On to enforce type safety and prevent implicit conversions that might cause runtime errors.

9.4 Scope of Declaration

The scope of a variable determines where it can be accessed in your program. Visual Basic 2019 provides different keywords to control variable scope.

Dim Keyword

Declares a local variable accessible only within the current procedure or block.

Dim localVar As Integer = 10

Static Keyword

Preserves the value of a local variable between procedure calls.

Static counter As Integer = 0

Public Keyword

Declares a global variable accessible by all procedures and modules.

Public globalVar As String = "Hello"

Scope Comparison

Table 9.2: Variable Scope Comparison
Keyword Scope Lifetime Example
Dim Local to procedure or block While procedure is executing Dim x As Integer
Static Local to procedure Entire program execution Static count As Integer
Public Entire application Entire program execution Public appName As String

9.5 Declaring Constants

Constants are different from variables in that their values do not change during program execution. The syntax to declare a constant is:

Const ConstantName As DataType = Value

Important Notes

Constants must be initialized when declared and cannot be changed later. Use constants for values that are fixed and used multiple times in your program, such as mathematical constants, configuration values, or fixed strings.

Example 9.4: Using Constants

This example calculates the area of a circle using the constant Pi.

Form1.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Declare a constant for Pi
    Const Pi As Single = 3.142
    
    ' Declare and initialize radius
    Dim R As Single = 10
    
    ' Calculate area of circle
    Dim AreaCircle As Single
    AreaCircle = Pi * R ^ 2
    
    ' Display result
    MsgBox("Area of circle with radius " & R & " = " & AreaCircle)
End Sub

Output:

> Result: "Area of circle with radius 10 = 314.2"
Area calculation result
Figure 9.4: Area calculation result

Lesson Summary

In this lesson, you've learned how to work with variables and constants in Visual Basic 2019:

Variable Naming

Understand the rules for naming variables in VB2019

Declaration

Use Dim to declare variables with appropriate data types

Assignment

Assign values to variables and avoid type mismatch errors

Scope

Control variable scope with Dim, Static, and Public

Constants

Declare and use constants for fixed values

You've learned how to declare, assign, and manage variables and constants in Visual Basic 2019. These are fundamental concepts that you'll use in every program you create. In the next lesson, we'll explore how to work with arrays.

Next Lesson

Ready to learn about arrays? Continue to Lesson 10: Creating Arrays.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More

VB2019 Paperback

Comprehensive guide to Visual Basic 2019

Get on Amazon